Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  55] [ 5]  / answers: 1 / hits: 16474  / 11 Years ago, wed, august 14, 2013, 12:00:00

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
}
});
}
}

})

More From » angularjs

 Answers
34

You could always listen to the keypress event and prevent the character from making it through. Here is a plunker



var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.validValues = ['a','1','2'];
});

app.directive('myValidator', function ($parse) {
return {
scope: {
validValues: '=validValues'
},
link: function (scope, elm, attrs) {
elm.bind('keypress', function(e){
var char = String.fromCharCode(e.which||e.charCode||e.keyCode), matches = [];
angular.forEach(scope.validValues, function(value, key){
if(char === value) matches.push(char);
}, matches);
if(matches.length == 0){
e.preventDefault();
return false;
}
});
}
}
});

[#76356] Monday, August 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hanna

Total Points: 66
Total Questions: 99
Total Answers: 101

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;