In AngularJS both $parsers and $validators can be used to validate forms. I was wondering what exactly the difference is between using a $parser and using a $validator.
Let's look at the following example:
Validation using a parser
angular.module("myFormApp")
.directive("containsWhiteSpace", containsWhiteSpace);
function containsWhiteSpace () {
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
return {
require: "ngModel",
link: function(scope, ele, attrs, ctrl){
ctrl.$parsers.unshift(function(value) {
if(value){
var isValid = !hasWhiteSpace(value);
ctrl.$setValidity('hasWhiteSpace', isValid);
}
return isValid ? value : undefined;
});
}
}
}
Validation using a validator
angular.module("myFormApp")
.directive("containsWhiteSpace", containsWhiteSpace);
function containsWhiteSpace () {
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
return {
require: "ngModel",
link: function(scope, ele, attrs, ctrl){
ctrl.$validators.hasWhiteSpace = function(value){
return !hasWhiteSpace(value);
}
}
}
}
They both do the same thing, but when is it correct to use a parser and when is it correct to use a validator? What are the advantages of both? What are the differences?
$parsers
are run in a pipeline, to transform the input value. They can return undefined
if they fail to parse the input, indicating a parse error. If the input value fails to parse, the validators are not run.
$validators
are run after parsers, on the parsed value. They can return false
to indicate a data error.
Basically
For example, consider a model requiring a positive number. $parsers
can call parseFloat
on the value, and $validators
can check if the value is positive.
For the example you gave, I think $validators
are more appropriate (and cleaner).
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