Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs validate input and prevent change if invalid

I neeed an input field where I can enter only the values 1,2 or 3 so i'm trying to build a directive which prevents all changes to the model if it doesn't match these values.
eg the value is 1 and I change it to 5 it should be still 1.

I've put together a small fiddle http://jsfiddle.net/kannix/Q5YKE/ but it's most likely wrong to use the $parsers.

app.directive('myvalidator', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            var validValues = [1,2,3];
            ctrl.$parsers.push(function (value) {
                if (validValues.indexOf(value) === -1){
                    //what to do here? should refuse wrong value and leave the old one
                }   
            });
        }
    }   

})
like image 611
kannix Avatar asked Nov 27 '22 01:11

kannix


2 Answers

I recently wrote a directive just for this. It takes a regExp object that validates the incoming key presses and only permits them if are valid:

// forces keystrokes that satisfy the regExp passed
app.directive("regExpRequire", function() {

    var regexp;
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            regexp = eval(attrs.regExpRequire);

            var char;
            elem.on("keypress", function(event) {
                char = String.fromCharCode(event.which)
                if(!regexp.test(elem.val() + char))
                    event.preventDefault();
            })
        }
    }

})

Template usage: <input type="text" reg-exp-require="/^[a-zA-Z]$/">

Or in your case: <input type="text" reg-exp-require="/^[1-3]*$/">

like image 120
Ian Haggerty Avatar answered Dec 09 '22 17:12

Ian Haggerty


I'd recommend using the ng-pattern-restrict directive.

Get the library and simply decorate your input like so:

<input type="text" pattern="[0-9]+" ng-pattern-restrict />

GitHub: AlphaGit/ng-pattern-restrict

like image 37
Mobiletainment Avatar answered Dec 09 '22 19:12

Mobiletainment