How to add custom validation to an AngularJS form?

后端 未结 12 1667
既然无缘
既然无缘 2020-11-22 10:07

I have a form with input fields and validation setup by adding the required attributes and such. But for some fields I need to do some extra validation. How wou

12条回答
  •  暖寄归人
    2020-11-22 10:39

    Custom Validations that call a Server

    Use the ngModelController $asyncValidators API which handles asynchronous validation, such as making an $http request to the backend. Functions added to the object must return a promise that must be resolved when valid or rejected when invalid. In-progress async validations are stored by key in ngModelController.$pending. For more information, see AngularJS Developer Guide - Forms (Custom Validation).

    ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
      var value = modelValue || viewValue;
    
      // Lookup user by username
      return $http.get('/api/users/' + value).
         then(function resolved() {
           //username exists, this means validation fails
           return $q.reject('exists');
         }, function rejected() {
           //username does not exist, therefore this validation passes
           return true;
         });
    };
    

    For more information, see

    • ngModelController $asyncValidators API

    • AngularJS Developer Guide - Forms (Custom Validation).


    Using the $validators API

    The accepted answer uses the $parsers and $formatters pipelines to add a custom synchronous validator. AngularJS 1.3+ added a $validators API so there is no need to put validators in the $parsers and $formatters pipelines:

    app.directive('blacklist', function (){ 
       return {
          require: 'ngModel',
          link: function(scope, elem, attr, ngModel) {           
              ngModel.$validators.blacklist = function(modelValue, viewValue) {
                  var blacklist = attr.blacklist.split(',');
                  var value = modelValue || viewValue;
                  var valid = blacklist.indexOf(value) === -1;
                  return valid;
              });    
          }
       };
    });
    

    For more information, see AngularJS ngModelController API Reference - $validators.

提交回复
热议问题