简体   繁体   中英

AngularJS directive for validation

I am trying create a custom directive to validate an input field's text against a list.

For example I have a list defined in my controller:

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

and my directive looks something like this:

 .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;
          }
        });
    }
  }; 
}); 

So I can compare a list in my view like so:

<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>

But I am a little stuck and I think my directive needs some tweaking but I am not sure. Thanks in advance for your help!

I have added several modifications to your original code it has so many typos and misleadings. And I adapt it to be up-to-date with the last release of AngularJS (1.3.x) api.

Directive

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>

Look this in action at Fiddler

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

I hope this is what you was looking for,

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM