[英]How do I restrict an input to only accept numbers?
我在 AngularJS 中使用 ngChange 來觸發一個自定義函數,該函數將刪除用戶添加到輸入中的任何字母。
<input type="text" name="inputName" data-ng-change="numbersOnly()"/>
問題是我需要定位觸發numbersOnly()
的輸入,以便我可以刪除輸入的字母。 我在谷歌上搜索了很長時間,但找不到任何關於此的信息。
我能做什么?
簡單的方法,如果它適用於您的用例,請使用type="number" :
<input type="number" ng-model="myText" name="inputName">
另一種簡單的方法: ng-pattern也可用於定義一個正則表達式,該表達式將限制該字段中允許的內容。 另請參閱有關表單的“食譜”頁面。
黑客? way , $watch 控制器中的 ng-model:
<input type="text" ng-model="myText" name="inputName">
控制器:
$scope.$watch('myText', function() {
// put numbersOnly() logic here, e.g.:
if ($scope.myText ... regex to look for ... ) {
// strip out the non-numbers
}
})
最好的方法,在指令中使用 $parser。 我不會重復@pkozlowski.opensource 提供的已經很好的答案,所以這里是鏈接: https ://stackoverflow.com/a/14425022/215945
所有上述解決方案包括使用NG-模型,這使得發現this
是不必要的。
使用 ng-change 會導致問題。 請參閱AngularJS - $scope.value 的重置不會改變模板中的值(隨機行為)
在文本字段上使用ng-pattern
:
<input type="text" ng-model="myText" name="inputName" ng-pattern="onlyNumbers">
然后將其包含在您的控制器上
$scope.onlyNumbers = /^\d+$/;
這是我對@Mark Rajcok 推薦為最佳方法的$parser
解決方案的實現。 它本質上是@pkozlowski.opensource出色的 $parser 文本答案,但重寫為僅允許數字。 所有功勞都歸功於他,這只是為了節省您閱讀該答案的 5 分鍾時間,然后重寫您自己的答案:
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;
});
}
};
});
你會像這樣使用它:
<input type="text" name="number" ng-model="num_things" numeric-only>
有趣的是,除非被字母數字包圍,否則空格永遠不會到達解析器,因此您必須根據需要使用.trim()
。 此外,該分析器不工作在<input type="number">
出於某種原因,非數字永遠不會進入解析器將它們刪除的地方,但它們確實進入了輸入控件本身。
提出的解決方案都沒有對我有用,幾個小時后我終於找到了方法。
這是角度指令:
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();
}
});
}
}
});
輸入看起來像:
<input type="number" min="0" name="inputName" ng-model="myModel" restrict-to="[0-9]">
正則表達式計算按下的鍵,而不是 value 。
它也可以完美地與輸入type="number"
因為它可以防止更改其值,因此該鍵永遠不會顯示並且不會與模型混淆。
這里是一個不錯的解決方案,也只允許輸入數字的input
:
<input type="text" ng-model="myText" name="inputName" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
有幾種方法可以做到這一點。
您可以使用type="number"
:
<input type="number" />
或者 - 我為此創建了一個使用正則表達式的可重用指令。
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;
}
});
}
};
}]);
}());
以上所有解決方案都很大,我想為此付出 2 美分。
我只是檢查輸入的值是否是數字,並檢查它是否不是空白,僅此而已。
這是html:
<input type="text" ng-keypress="CheckNumber()"/>
這是JS:
$scope.CheckKey = function () {
if (isNaN(event.key) || event.key === ' ' || event.key === '') {
event.returnValue = '';
}
};
這很簡單。
我相信這不會在 Paste 上工作,只是眾所周知。
對於粘貼,我認為您需要使用 onChange 事件並解析整個字符串,這是另一種野獸。 這是特定於打字的。
Paste 更新:只需添加此 JS 函數:
$scope.CheckPaste = function () {
var paste = event.clipboardData.getData('text');
if (isNaN(paste)) {
event.preventDefault();
return false;
}
};
並且 html 輸入添加觸發器:
<input type="text" ng-paste="CheckPaste()"/>
我希望這有助於o/
這是一個處理上述命題不處理的任何情況的Plunker 。
通過使用 $formatters 和 $parsers 管道並避免 type="number"
這是問題/解決方案的解釋(也可在 Plunker 中找到):
/*
*
* 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)
*
*/
<input type="text" name="profileChildCount" id="profileChildCount" ng-model="profile.ChildCount" numeric-only maxlength="1" />
您可以使用僅數字屬性。
十進制
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);
}
};
});
數字
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);
}
};
});
我知道這是舊的,但我為此目的創建了一個指令,以防有人正在尋找一個簡單的解決方案。 使用起來非常簡單。
你可以在這里查看。
您可能還想刪除輸入開頭的 0 ......我只是在上面的 Mordred 答案中添加了一個 if 塊,因為我還不能發表評論......
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;
});
}
};
})
基本 HTML
<input type="number" />
基本引導程序
<input class="form-control" type="number" value="42" id="my-id">
試試這個,
<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();
}
}
解決方案:我為應用程序中的所有輸入、數字、文本或任何輸入制定了指令,因此您可以輸入一個值並更改事件。 制作角度 6
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector: 'input[inputType]'
})
export class InputTypeDirective {
constructor(private _el: ElementRef) {}
@Input() inputType: string;
// tipos: number, letter, cuit, tel
@HostListener('input', ['$event']) onInputChange(event) {
if (!event.data) {
return;
}
switch (this.inputType) {
case 'number': {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if (initalValue !== this._el.nativeElement.value) {
event.stopPropagation();
}
break;
}
case 'text': {
const result = event.data.match(/[^a-zA-Z Ññ]*/g);
if (result[0] !== '') {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(
/[^a-zA-Z Ññ]*/g,
''
);
event.stopPropagation();
}
break;
}
case 'tel':
case 'cuit': {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(/[^0-9-]*/g, '');
if (initalValue !== this._el.nativeElement.value) {
event.stopPropagation();
}
}
}
}
}
HTML
<input matInput inputType="number" [formControlName]="field.name" [maxlength]="field.length" [placeholder]="field.label | translate" type="text" class="filter-input">
我最終創建了上述代碼的修改指令以接受輸入並即時更改格式...
.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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.