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
}
});
}
}
})
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]*$/">
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With