Rectangle 27 0

javascript Using an AngularJS directive, how do I bind to keyup event on input field and revert model to previous value if it fails a regular expression check?


ngModelCtrl.$parsers.push( function (value) {
    // do some validation logic...it fails
    if (validationFails) {
        var prevValue = ctrl.$modelValue;
        ctrl.$setViewValue(prevValue); // set view
        ctrl.$render(); // render view
        return prevValue; // set model
    }

    // otherwise we're good!
    return value;
} );

Ah yes sorry $validators is to modify the validity of the form input, I'll modify the answer to use $parsers.

As I read the docs more, maybe you need to call ngModelCtrl.$setViewValue(prevValue) in the validationFails block before returning prevValue. I might set up a plunkr to test this.

Gave this a try, I am able to maintain the correct "prevValue" but it still shows the bad value in the UI. Can I prevent the model update from this function?

Here is a Plunker which demonstrates. The input field will reject a lowercase z from being entered.

Thanks for your reply. I gave this a try but it doesn't revert back to the old value when I return false.

This would be a good time to use ngModelCtrl.$parsers instead of binding to keypresses manually. Try something like this in your link function:

Note
Rectangle 27 0

javascript Using an AngularJS directive, how do I bind to keyup event on input field and revert model to previous value if it fails a regular expression check?


<input type="text" 
       class="form-control" 
       ng-model="item.paymentAmount" 
       ng-pattern="currencyRegEx" />

Firstly, I think you shouldn't modify the input of the user. I personnaly find it bad on a UX point of view. It's better to indicate that the input is in an error state by bordering in red for example.

Secondly, there is a directive that can fit your need, ng-pattern.

Thanks for your reply. I tried using ng-pattern but it doesn't seem to be what I need. I agree that we shouldn't modify the user input, but this is a requirement for our project :(

Note