Reputation: 2725
I am trying to set custom validation on an input field in an Angular app. The validation cannot be set to a pattern, since it is based on the content of another field (e.i. Passwords must match)
A way to do validation in this case is to check for the fields on form input. However, I want to be able to check for the validity in real time, and be able to use CSS classes such as .ng-dirty
and .ng-valid
, which come when Angular takes care of validation.
I tried to use $scope.formName.inputName.$setValidity(...)
, but I am running into issues on that end (StackOverflow question here).
Is there another way in AngularJS to set custom validation?
Upvotes: 0
Views: 124
Reputation: 364
As mentioned if you check https://docs.angularjs.org/guide/forms#custom-validation You'll see you can use directives to create your own custom validations, in the example provided the validation is done whenever you input a character.
If you use your browser to inspect the example (username input field) you'll see the classes (ng-not-empty ng-dirty ng-valid-parse ng-touched ng-valid ng-valid-username) being changed on the fly.
If you had a form these classes would be taken into account to change the form.$valid property to true or false. By default if form.$valid is false then you can't submit it.
Upvotes: 1
Reputation: 1296
I know this doesnt answer to your question but I found a couple of directives that can do that for you:
https://blog.brunoscopelliti.com/angularjs-directive-to-check-that-passwords-match/
https://github.com/TheSharpieOne/angular-validation-match
Try it out to see if its what you need.
Upvotes: 0