AngularJS指令用于验证

时间:2015-06-05 23:35:31

标签: javascript html angularjs angularjs-directive

我正在尝试创建一个自定义指令来根据列表验证输入字段的文本。

例如,我在控制器中定义了一个列表:

$scope.examples = [
        {"name":"Jeff"},
        {"name":"John"},
        {"name":"Sarah"},
        {"name":"Julie"}
      ];

我的指令看起来像这样:

 .directive('customValidation', function () {
  return {
    restrict:'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ctrl) {
        ctrl.$parsers.unshift(function(input){
          if(input === scope[attrs.customValidation]) {
            ctrl.$setValidity('customValidation', true);
            return input;
          }
          else {
            ctrl.$setValidity('customValidation', false);
            return undefined;
          }
        });
    }
  }; 
}); 

所以我可以在我的视图中比较一个列表:

<form name = "form">

  <ul>
      <li ng-repeat="item in examples" name='list' ng-model="item.name">     
       {{item.name}}</li>
  </ul>

  <input type='text' id='input' required name='input'    
  custom-validation='item.name' ng-model='input2'>   

  <p ng-show='form.input2.$valid'>Already a name</p>

  <button ng-disabled="form.$valid">Add user</button>

但我有点陷入困境,我认为我的指令需要一些调整,但我不确定。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我在您的原始代码中添加了一些修改,它有很多错别字和误导。我将它改编为最新版本的AngularJS(1.3.x)api。

指令

myApp.directive('customValidation', function() {
    return {
        restrict: 'AE',
        require: 'ngModel',
        scope: {
            collection: '=',
            property: '@'
        },
        link: function(scope, element, attrs, ctrl) {
            ctrl.$validators.customValidation = function(model, viewValue) {
                // Check if viewValue is not empty (:
                if (!ctrl.$isEmpty(viewValue)) {
                    // Search in the collection if the username already exist.
                    var tot = scope.collection.filter(function(x) {
                        return x[scope.property].toUpperCase() === viewValue.toUpperCase()
                    });

                    // Other user(s) with the same name has been founded.
                    if (tot.length > 0)
                        return true;                        
                }                
                // Valid state.
                return false;
            }
        }
    }
});

HTML

<form name="form">
    <ul>
        <li ng-repeat="item in examples" name='list' ng-model="item.name">
            {{item.name}}</li>
    </ul>

    <input type='text' id='input' required name='input' custom-validation collection="examples" property='name' ng-model='input2' />

    <p ng-show='!form.input.$error.customValidation'>Already a name</p>

    <button ng-disabled="form.$valid">Add user</button>
</form>

在Fiddler

中查看此内容

https://jsfiddle.net/8tptzocm/1/

我希望这就是你要找的东西,

干杯。