While performing some basic research on custom client-side validation in Angular.js, I was reading the ngModel.NgModelController documentation, and found the following cryptic line:
$setValidity(validationErrorKey, isValid); Change the validity state, and notifies the form.
This method can be called within $parsers/$formatters. However, if possible, please use the ngModel.$validators pipeline which is designed to call this method automatically.
A couple of hours and many Google (and StackOverflow!) searches later, I have found nothing about this ngModel.$validators
pipeline anywhere. All custom validation examples use the $parsers/$formatters
setup as below:
link: function (scope, elem, attr, ctrl) { // Other necessary logic... ctrl.$parsers.push(function () { // Validation logic ctrl.$setValidity('validation-type', true); }); ctrl.$formatters.push(function () { // Validation logic ctrl.$setValidity('validation-type', true); }); },
Question: The Angular documentation states that the above code is not the best practice, and that this mythical ngModel.$validators
pipline is the correct way to go. I have failed to find any information on this better practice. How does one use ngModel.$validators
to correctly implement this custom clientside validation?
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.
$setValidity(validationErrorKey, isValid); Change the validity state, and notify the form. This method can be called within $parsers/$formatters or a custom validation implementation. However, in most cases it should be sufficient to use the ngModel. $validators and ngModel.
Model updates and validation By setting the allowInvalid property to true, the model will still be updated even if the value is invalid.
AngularJS includes the following validation directives. Sets required attribute on an input field. Sets minlength attribute on an input field. Sets maxlength attribute on an input field.
$validators
are new to Angular 1.3. This blog post gives a good explanation on how to use them: http://www.yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html#the-validators-pipeline
The basic idea is that you add a function onto ngModel.$validators
that returns a boolean
specifying whether the model is valid.
Then you can refrence that validator in your HTML the same way you would reference any built in validators. e.g.
<div ng-if="myForm.myField.$error.myValidator"> some error message here </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With