Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: $parsers vs $validators

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?

like image 316
koningdavid Avatar asked Jun 24 '15 14:06

koningdavid


1 Answers

$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

  • use parsers to coerce a string input value into the data type you need/expect.
  • use validators to validate a value of the correct data type.

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).

like image 122
Igor Raush Avatar answered Sep 30 '22 01:09

Igor Raush