Nav
Nav

Reputation: 4540

how we can get which validation is invalid in AngularJS

I have this code to figure out if the element is valid or invalid in my directive :

myModule.directive('myDirective',function(){
return {
    restrict: 'A',
    scope: {},
    require:'ngModel',
    link: function(scope,element,attrs,ctrl){

        if(ctrl.$invalid){
            //do something
        }
    }
}});

So my problem is how can I determine which type of validation is invalid, required? max-length? my other custom-validations?

Because I need to generate proper validation-message to show.

Upvotes: 0

Views: 59

Answers (2)

brianmarco
brianmarco

Reputation: 353

It sounds like you might need to look into $error of your ctrl object.

Take a look at the following:

https://docs.angularjs.org/guide/forms#custom-validation

Look for references of $error. There are some specific examples there that might be of help to you.

For example:

<div ng-show="form.uEmail.$dirty && form.uEmail.$invalid">Invalid:
  <span ng-show="form.uEmail.$error.required">Tell us your email.</span>
  <span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>

Upvotes: 1

Sunil D.
Sunil D.

Reputation: 18193

NgModelController (or ctrl, in your example) has an $error property that you can use to see what the validation errors are.

So if the "required" validation has failed, this property will be truthy: ctrl.$error.required

Upvotes: 1

Related Questions