0

How can I make the validation set form.$valid to false when the initial value is not valid (model is pristine). If I manually change the input, the form.$valid is corrected based on the input.

http://plnkr.co/edit/lDrsCFez8PkROuEC6wvC?p=preview (This is based on the integer directive from the Custom Validation section in https://docs.angularjs.org/guide/forms.)

2 Answers 2

1

In your directive you only specify a $parser.
A $parser takes effect when the $viewValue is changed, i.e. through interaction with the view (or programmatically setting the $viewValue).

But you are not touching the $viewValue, only the $modelValue.
If you want to perform validation when the $modelValue changes, you need to specify a $formatter as well.


E.g. add the following code in your linking function:

ctrl.$formatters.push(function (modelValue) {
    if (modelValue && !INTEGER_REGEXP.test(modelValue)) {
        ctrl.$setValidity('integer', false);
    } else {
        ctrl.$setValidity('integer', true);
    }
    // Return the original value regardless of its validity,
    // so it shows up in the view (even if it is invalid).
    return modelValue;
});

See, also, this short demo.


UPDATED:

I updated the code above and the demo to take into account the case of empty values and also properly re-validate when the $modelValue is changed programmatically.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! And thank you for taking the time to explain as well!
Could you explain why I need (or should) not call $setValidity with true if the regexp.test is valid?
@jostyposty: I can't explain that :) Your question made me realize that you should and you should also take into account empty values (usually validation should not be applied on empty values). Take a look at my updated demo (and answer).
0

Why don't you use type="number"

<input type="number" ng-model="size" name="size" />

1 Comment

I don't like the way some browsers creates stuff inside the input when using number. Like up and down arrows. Also, in a float directive I'm creating, I need the user to be able to write 1,2 which is not a valid number. I guess I like to keep things consistent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.