n-canter
n-canter

Reputation: 288

Data validation with custom directive before user inputs smth

I'm trying to validate data on my form using my own directive, but the data is validated only after user inputs something not right after binding.

myApp.directive('dvCyrillic', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        var CYRILLIC_REGEX = /^[а-яё -]+$/i;
        if (CYRILLIC_REGEX.test(viewValue) || viewValue.length == 0) {
          // it is valid
          ctrl.$setValidity('cyrillic', true);
          return viewValue;
        } else {
          // it is invalid, return undefined (no model update)
          ctrl.$setValidity('cyrillic', false);
          return undefined;
        }
      });
    }
  };
});

Here is an example. How can I validate data before user inputs smth?

Upvotes: 1

Views: 211

Answers (1)

Simon Belanger
Simon Belanger

Reputation: 14870

The $parsers will only validate from the View to the Model while the $formatters will validate from the Model to the View. You can refactor your validation in a separate method and add your validation to both the parsers and formatters:

var CYRILLIC_REGEX = /^[а-яё -]+$/i;
ctrl.$parsers.unshift(validate);
ctrl.$formatters.unshift(validate);

function validate(viewValue) {
  if (CYRILLIC_REGEX.test(viewValue) || viewValue.length == 0) {
    // it is valid
    ctrl.$setValidity('cyrillic', true);
    return viewValue;
  } else {
    // it is invalid, return undefined (no model update)
    ctrl.$setValidity('cyrillic', false);
    return undefined;
  }
}

Here's the updated fiddle

Upvotes: 1

Related Questions