Sharikov Vladislav
Sharikov Vladislav

Reputation: 7269

How to add directive for extra validation properly in angular?

What I need: I need to add extra validation to input by adding attribute to this input.

Firstly, my plnkr example is here

What I'd tried?: I added directive, so when I add attribute to the input, the value of the input is being validated by regexp ^5$. Also, I added required to the input. I am talking about 2nd input now (name of the input is input2).

So, I'd added attributes "my-attribute" and "required". When there is nothing in input I expect two items in myForm.item[1].$error: its ok – there are properties myAttribute and required. Now, I will add some to the input2, for example "abc", now I expect in myForm.item[1].$error only myAttribute property (because required validation is passed, but myAttribute validation is not), but there is properties myAttribute and parse in myForm.item[1].$error. What is parse property? Why it is adding to $error?

I should notice, that when I put 5 to the input2 myForm.item[1].$error is empty, because both require and myAttribute validations passed (and this behaviour is expected).

Now, when I clear input2 there are properties parse and myAttribute again. Why? When field input2 is empty, I expect required and myAttribute in myForm.item[1].$error, but there are no ones.

So, why I get strange property parse in $error and how I can make my example working?

Form example code was founded here and approach to validate input by directive was founded in answer to this post.

Upvotes: 0

Views: 75

Answers (1)

bmleite
bmleite

Reputation: 26880

What is parse property? Why it is adding to $error?

The parse property is automatically added by Angular when one of the parsers returns undefined. From Angular documentation:

Returning undefined from a parser means a parse error occurred. No $validators will run and the 'ngModel' will not be updated until the parse error is resolved. The parse error is stored in 'ngModel.$error.parse'.

Not sure if I'm missing some use case here but changing the return clause from the parser should be enough:

//For DOM -> model validation
ngModel.$parsers.unshift(function(value) {
  var valid = new RegExp("^5$").test(value);
  ngModel.$setValidity('myAttribute', valid);
  return value;
});

Upvotes: 2

Related Questions