How to add custom validation to an AngularJS form?

后端 未结 12 1684
既然无缘
既然无缘 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:44

    In AngularJS the best place to define Custom Validation is Cutsom directive. AngularJS provide a ngMessages module.

    ngMessages is a directive that is designed to show and hide messages based on the state of a key/value object that it listens on. The directive itself complements error message reporting with the ngModel $error object (which stores a key/value state of validation errors).

    For custom form validation One should use ngMessages Modules with custom directive.Here i have a simple validation which will check if number length is less then 6 display an error on screen

     
    Too Short

    Here is how to create custom validation directive

    angular.module('myApp',['ngMessages']);
            angular.module('myApp',['ngMessages']).directive('customValidation',function(){
                return{
                restrict:'A',
                require: 'ngModel',
                link:function (scope, element, attr, ctrl) {// 4th argument contain model information 
    
                function validationError(value) // you can use any function and parameter name 
                    {
                     if (value.length > 6) // if model length is greater then 6 it is valide state
                     {
                     ctrl.$setValidity('invalidshrt',true);
                     }
                     else
                     {
                     ctrl.$setValidity('invalidshrt',false) //if less then 6 is invalide
                     }
    
                     return value; //return to display  error 
                    }
                    ctrl.$parsers.push(validationError); //parsers change how view values will be saved in the model
                }
                };
            });
    

    $setValidity is inbuilt function to set model state to valid/invalid

提交回复
热议问题