在电子邮件字段中取消不需要的字符

时间:2016-06-14 07:39:56

标签: angularjs

我有一个半工作的AngularJS指令,它的作用是否定字段上的特殊字符等不需要的字符。它取决于该指令的属性。问题是它不适用于电子邮件领域。我想知道为什么..这是我的代码:

<!DOCTYPE html>
<html >

<head>
  <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>

<body ng-app="ngToggle">
  <div>
      <input type="text" ng-model="textModel" class="uncheck" negate-special-characters>
      <input type="text" ng-model="textModel2" class="uncheck" negate-special-characters="address">
      <input type="text" ng-model="textModel3" class="uncheck" negate-special-characters="name">
      <input type="email" ng-model="textModel4" class="uncheck" negate-special-characters="e-mail">
  </div>
  <script type="text/javascript">
        angular.module('ngToggle', [])
        .directive('negateSpecialCharacters', function(){
          return{
            require: 'ngModel',
            link: function(scope, element, attrs, ngModel){
                attrs.$observe('ngModel', function(value){
                    scope.$watch(value, function(newValue){
                      try{
                      if(attrs.negateSpecialCharacters){
                            if(attrs.negateSpecialCharacters == "address"){
                                  regex = /[^a-zA-Z0-9,. ]+/g;
                            }
                            else if(attrs.negateSpecialCharacters == "name"){
                               regex = /[^a-zA-Z- ]+/g;
                            }
                            else if(attrs.negateSpecialCharacters == "e-mail"){
                                 regex = /[^a-zA-Z_0-9@. ]+/g;
                              }
                        }else{
                            regex = /[^a-zA-Z0-9 ]+/g;
                        }
                        clean = newValue.replace(regex, "");
                        ngModel.$setViewValue(clean);
                        ngModel.$render();
                      }catch(err){
                            // Just to catch all the regex errors upon page reload
                            console.log(err);
                    }
                    });
                });
            }
        }
        });
  </script>
</body>

以下是plunkr:http://plnkr.co/edit/Rv5h5ZvztSqGuCXTZ8Y2?p=preview

0 个答案:

没有答案