Comment puis-je restreindre une entrée à n'accepter que des nombres?
j'utilise ngChange dans AngularJS pour déclencher une fonction personnalisée qui supprimera toutes les lettres que l'utilisateur ajoute à l'entrée.
<input type="text" name="inputName" data-ng-change="numbersOnly()"/>
le problème est que je dois cibler l'entrée qui a déclenché numbersOnly()
afin que je puisse supprimer les lettres entrées. J'ai cherché longtemps et durement sur Google et n'ai pas été en mesure de trouver quoi que ce soit à ce sujet.
Que puis-je faire?
15 réponses
Easy way , utilisez type=" Nombre " si cela fonctionne pour votre cas d'utilisation:
<input type="number" ng-model="myText" name="inputName">
une Autre façon très simple: ng-pattern peut également être utilisé pour définir un regex qui limitera ce qui est autorisé dans le champ. Voir aussi la page " cookbook "à propos des formulaires .
Hackish? chemin , $ regarder le ng-modèle dans votre contrôleur:
<input type="text" ng-model="myText" name="inputName">
contrôleur:
$scope.$watch('myText', function() {
// put numbersOnly() logic here, e.g.:
if ($scope.myText ... regex to look for ... ) {
// strip out the non-numbers
}
})
Meilleure façon , utiliser un $parser dans une directive. Je ne vais pas répéter la réponse déjà bonne fournie par @pkozlowski.opensource, donc voici le lien: https://stackoverflow.com/a/14425022/215945
toutes les solutions ci-dessus impliquent l'utilisation du modèle ng, ce qui rend la recherche this
inutile.
utiliser ng-change posera des problèmes. Voir AngularJS - remise à zéro de $champ d'application.la valeur ne change pas la valeur dans le modèle (comportement aléatoire)
en utilisant ng-pattern
sur le champ de texte:
<input type="text" ng-model="myText" name="inputName" ng-pattern="onlyNumbers">
alors incluez ceci sur votre contrôleur
$scope.onlyNumbers = /^\d+$/;
voici ma mise en œuvre de la solution $parser
que @Mark Rajcok recommande comme meilleure méthode. C'est essentiellement @pkozlowski.opensource excellente $analyseur de réponse en texte mais réécrit pour autoriser uniquement les objets numériques. Tout le crédit va à lui, c'est juste pour vous sauver les 5 minutes de la lecture de cette réponse et puis réécrire votre propre:
app.directive('numericOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
et vous l'utilisez comme ceci:
<input type="text" name="number" ng-model="num_things" numeric-only>
Il est intéressant de noter que les espaces n'atteignent jamais l'analyseur, à moins d'être entourés d'un alphanumérique, donc vous devez .trim()
au besoin. En outre, cet analyseur ne pas travailler sur <input type="number">
. Pour une raison quelconque, les non-numériques ne se rendent jamais à l'analyseur où ils seraient retirés, mais ils font le font dans le contrôle d'entrée lui-même.
aucune des solutions proposées ne fonctionnait bien pour moi, et après quelques heures j'ai finalement trouvé le chemin.
C'est la directive angulaire:
angular.module('app').directive('restrictTo', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var re = RegExp(attrs.restrictTo);
var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;
element[0].addEventListener('keydown', function(event) {
if (!exclude.test(event.key) && !re.test(event.key)) {
event.preventDefault();
}
});
}
}
});
Et l'entrée ressemblerait à:
<input type="number" min="0" name="inputName" ng-model="myModel" restrict-to="[0-9]">
l'expression régulière évalue la touche pressée, pas la valeur .
il fonctionne également parfaitement avec les entrées type="number"
parce qu'empêche de changer son valeur, de sorte que la clé n'est jamais affichée et il ne touche pas le modèle.
il y a plusieurs façons de le faire.
vous pouvez utiliser type="number"
:
<input type="number" />
alternativement-j'ai créé un réutilisable directive pour cela qui utilise une expression régulière.
Html
<div ng-app="myawesomeapp">
test: <input restrict-input="^[0-9-]*$" maxlength="20" type="text" class="test" />
</div>
Javascript
;(function(){
var app = angular.module('myawesomeapp',[])
.directive('restrictInput', [function(){
return {
restrict: 'A',
link: function (scope, element, attrs) {
var ele = element[0];
var regex = RegExp(attrs.restrictInput);
var value = ele.value;
ele.addEventListener('keyup',function(e){
if (regex.test(ele.value)){
value = ele.value;
}else{
ele.value = value;
}
});
}
};
}]);
}());
voici un Plunker manipulation de toute situation au-dessus de la proposition ne pas manipuler.
En utilisant $ formatters et $parsers pipeline et en évitant type= "Nombre "
et voici l'explication des problèmes / solutions (également disponible dans le plongeur):
/*
*
* Limit input text for floating numbers.
* It does not display characters and can limit the Float value to X numbers of integers and X numbers of decimals.
* min and max attributes can be added. They can be Integers as well as Floating values.
*
* value needed | directive
* ------------------------------------
* 55 | max-integer="2"
* 55.55 | max-integer="4" decimal="2" (decimals are substracted from total length. Same logic as database NUMBER type)
*
*
* Input type="number" (HTML5)
*
* Browser compatibility for input type="number" :
* Chrome : - if first letter is a String : allows everything
* - if first letter is a Integer : allows [0-9] and "." and "e" (exponential)
* Firefox : allows everything
* Internet Explorer : allows everything
*
* Why you should not use input type="number" :
* When using input type="number" the $parser pipeline of ngModel controller won't be able to access NaN values.
* For example : viewValue = '1e' -> $parsers parameter value = "".
* This is because undefined values are not allowes by default (which can be changed, but better not do it)
* This makes it impossible to modify the view and model value; to get the view value, pop last character, apply to the view and return to the model.
*
* About the ngModel controller pipelines :
* view value -> $parsers -> model value
* model value -> $formatters -> view value
*
* About the $parsers pipeline :
* It is an array of functions executed in ascending order.
* When used with input type="number" :
* This array has 2 default functions, one of them transforms the datatype of the value from String to Number.
* To be able to change the value easier (substring), it is better to have access to a String rather than a Number.
* To access a String, the custom function added to the $parsers pipeline should be unshifted rather than pushed.
* Unshift gives the closest access to the view.
*
* About the $formatters pipeline :
* It is executed in descending order
* When used with input type="number"
* Default function transforms the value datatype from Number to String.
* To access a String, push to this pipeline. (push brings the function closest to the view value)
*
* The flow :
* When changing ngModel where the directive stands : (In this case only the view has to be changed. $parsers returns the changed model)
* -When the value do not has to be modified :
* $parsers -> $render();
* -When the value has to be modified :
* $parsers(view value) --(does view needs to be changed?) -> $render();
* | |
* | $setViewValue(changedViewValue)
* | |
* --<-------<---------<--------<------
*
* When changing ngModel where the directive does not stand :
* - When the value does not has to be modified :
* -$formatters(model value)-->-- view value
* -When the value has to be changed
* -$formatters(model vale)-->--(does the value has to be modified) -- (when loop $parsers loop is finished, return modified value)-->view value
* |
* $setViewValue(notChangedValue) giving back the non changed value allows the $parsers handle the 'bad' value
* | and avoids it to think the value did not changed
* Changed the model <----(the above $parsers loop occurs)
*
*/
décimal
directive('decimal', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits.split('.').length > 2) {
digits = digits.substring(0, digits.length - 1);
}
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
chiffres
directive('entero', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var value = val + ''; //convert to string
var digits = value.replace(/[^0-9]/g, '');
if (digits !== value) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
je sais que c'est ancien, mais j'ai créé une directive à cet effet au cas où quelqu'un cherche une solution facile. Très simple à utiliser.
Vous pouvez le vérifier ici .
vous pouvez également supprimer le 0 au début de l'entrée... J'ajoute simplement un bloc if à la réponse Mordred ci-dessus parce que je ne peux pas encore faire de commentaire...
app.directive('numericOnly', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
//clear beginning 0
if(transformedInput == 0){
modelCtrl.$setViewValue(null);
modelCtrl.$render();
}
return transformedInput;
});
}
};
})
de Base et HTML propre chemin
<input type="number" />
<input type="text" name="profileChildCount" id="profileChildCount" ng-model="profile.ChildCount" numeric-only maxlength="1" />
vous pouvez utiliser l'attribut numérique seulement .
Voici une assez bonne solution pour ne permettre que le numéro enter du input
:
<input type="text" ng-model="myText" name="inputName" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
Essayez cette,
<input ng-keypress="validation($event)">
function validation(event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
j'ai fini par créer une directive modifiée du code ci-dessus pour accepter les entrées et changer le format à la volée...
.directive('numericOnly', function($filter) {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
element.bind('keyup', function (inputValue, e) {
var strinput = modelCtrl.$$rawModelValue;
//filter user input
var transformedInput = strinput ? strinput.replace(/[^,\d.-]/g,'') : null;
//remove trailing 0
if(transformedInput.charAt(0) <= '0'){
transformedInput = null;
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}else{
var decimalSplit = transformedInput.split(".")
var intPart = decimalSplit[0];
var decPart = decimalSplit[1];
//remove previously formated number
intPart = intPart.replace(/,/g, "");
//split whole number into array of 3 digits
if(intPart.length > 3){
var intDiv = Math.floor(intPart.length / 3);
var strfraction = [];
var i = intDiv,
j = 3;
while(intDiv > 0){
strfraction[intDiv] = intPart.slice(intPart.length-j,intPart.length - (j - 3));
j=j+3;
intDiv--;
}
var k = j-3;
if((intPart.length-k) > 0){
strfraction[0] = intPart.slice(0,intPart.length-k);
}
}
//join arrays
if(strfraction == undefined){ return;}
var currencyformat = strfraction.join(',');
//check for leading comma
if(currencyformat.charAt(0)==','){
currencyformat = currencyformat.slice(1);
}
if(decPart == undefined){
modelCtrl.$setViewValue(currencyformat);
modelCtrl.$render();
return;
}else{
currencyformat = currencyformat + "." + decPart.slice(0,2);
modelCtrl.$setViewValue(currencyformat);
modelCtrl.$render();
}
}
});
}
};
})
<input type="text" ng-model="employee.age" valid-input input-pattern="[^0-9]+" placeholder="Enter an age" />
<script>
var app = angular.module('app', []);
app.controller('dataCtrl', function($scope) {
});
app.directive('validInput', function() {
return {
require: '?ngModel',
scope: {
"inputPattern": '@'
},
link: function(scope, element, attrs, ngModelCtrl) {
var regexp = null;
if (scope.inputPattern !== undefined) {
regexp = new RegExp(scope.inputPattern, "g");
}
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (regexp) {
var clean = val.replace(regexp, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
}
else {
return val;
}
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
}}); </script>