숫자 만 허용되는 입력을 제한 귀하가 허용합니까?
AngularJS에서 ngChange를 사용하여 사용자가 입력에 추가하는 모든 문자를 제거하는 사용자 지정 함수를 트리거하고 있습니다.
<input type="text" name="inputName" data-ng-change="numbersOnly()"/>
문제는 입력 numbersOnly()
한 문자를 제거 할 필요가있는 트리거 된 입력 대상으로 할 수 있습니다. 나는 Google에서 길고 열심히하고 이것에 대해 아무것도 없습니다.
어떡해?
쉬운 방법 , 사용 유형 = "숫자" 가 사용 사례에 대해 작동하는 경우 :
<input type="number" ng-model="myText" name="inputName">
또 다른 쉬운 방법 : ng-pattern 을 사용하여 필드에서 허용되는 항목을 제한하는 정규식을 정의 할 수도 있습니다. 또한 참조 양식에 대한 "요리 책"페이지를 .
해 키시? 방법 , 컨트롤러에서 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-model을 사용하여 설치 this
가 필요 없습니다.
ng-change를 사용하면 문제가 발생합니다. AngularJS 참조 -$ scope.value라는 템플릿의 값을 변경하지 않습니다 (무작위 동작).
사용하여 ng-pattern
텍스트 필드에 :
<input type="text" ng-model="myText" name="inputName" ng-pattern="onlyNumbers">
그런 다음 컨트롤러에 포함
$scope.onlyNumbers = /^\d+$/;
제안 된 솔루션 중 어느 것도 나를 위해 잘 작동하지 갑자기 고 몇 시간 후에 마침내 방법을 찾았습니다.
이 각도 지시문입니다.
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]">
정규식 은 값이 아닌 키를 평가합니다 .
또한 type="number"
값을 변경하는 것을 방지하기 때문에 입력과 완벽하게 작동 엉망으로 만들지 않고 모델을 만들지 않습니다.
$parser
@Mark Rajcok이 최상의 방법으로 권장 하는 솔루션의 구현은 다음과 가변적 입니다. 포함으로 @ 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">
. 어떤 숫자, 숫자가 아닌 사람 은 제거 될 파서로 이동 하지 않지만 입력 컨트롤 자체로 만듭니다.
이를 수행하는 몇 가지 방법이 있습니다.
다음을 사용할 수 있습니다 type="number"
.
<input type="number" />
또는 정규식을 사용하는 가능한 지시문 을 만들었습니다 .
HTML
<div ng-app="myawesomeapp">
test: <input restrict-input="^[0-9-]*$" maxlength="20" type="text" class="test" />
</div>
자바 펼쳐
;(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;
}
});
}
};
}]);
}());
다음은 처리하지 않는 제안 위의 상황을 처리 하는 Plunker 입니다.
$ formatters 및 $ parsers 파이프 라인을 사용하고 type = "number"를 피하여
다음은 문제 / 해결 방법에 대한 설명입니다.
/*
*
* 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)
*
*/
위의 모든 솔루션은 상당히 준비되어 있습니다. 저는 이것에 대해 2 센트를주고 싶었습니다.
입력 한 값이 숫자인지 아닌지 확인하고 비어 있지 않은지 확인하는 것뿐입니다.
다음은 html입니다.
<input type="text" ng-keypress="CheckNumber()"/>
다음은 JS입니다.
$scope.CheckKey = function () {
if (isNaN(event.key) || event.key === ' ' || event.key === '') {
event.returnValue = '';
}
};
아주 간단합니다.
나는 작동하지 않을 것입니다.
넣기의 경우 onChange 이벤트를 사용하고 전체를 구문 분석해야합니다. 이것은 타이핑에 해당됩니다.
붙여 넣기 업데이트 :이 JS 함수를 추가하십시오.
$scope.CheckPaste = function () {
var paste = event.clipboardData.getData('text');
if (isNaN(paste)) {
event.preventDefault();
return false;
}
};
그리고 html 입력은 트리거를 추가합니다.
<input type="text" ng-paste="CheckPaste()"/>
이 정보가 도움이되기를 바랍니다.
소수
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);
}
};
});
나는 쉽게 사용할 수있는 방법을 찾을 수 있습니다. 사용이 매우 간단합니다.
여기에서 확인할 수 있습니다 .
아직 게임을 할 수 없기 때문에 위의 Mordred가 블록을 추가하기 위해서는 제거하고 싶을 수도 있습니다 ...
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 type="text" name="profileChildCount" id="profileChildCount" ng-model="profile.ChildCount" numeric-only maxlength="1" />
숫자 전용 속성을 사용할 수 있습니다.
다음은 숫자 입력 만 허용하는 꽤 좋은 솔루션입니다 input
.
<input type="text" ng-model="myText" name="inputName" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
이 시도,
<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>
참고 URL : https://stackoverflow.com/questions/14615236/how-do-i-restrict-an-input-to-only-accept-numbers
'ProgramingTip' 카테고리의 다른 글
jQuery.extend와 jQuery.fn.extend의 차이점은 무엇입니까? (0) | 2020.10.04 |
---|---|
저장 후 몽구스 채우기 (0) | 2020.10.04 |
Gradle로 라이브러리 프로젝트를 빌드 할 때 BuildConfig.DEBUG는 항상 false입니다. (0) | 2020.10.04 |
redux에서 특정 배열 항목 내부의 단일 값을 업데이트하는 방법 (0) | 2020.10.04 |
elisp에서 운영을 확인하는 방법은 무엇입니까? (0) | 2020.10.04 |