在Angular 6中仅允许带小数的正数 [英] Only allow positive numbers with only one decimal in Angular 6
问题描述
我是堆栈溢出的新手,所以如果我在任何地方出错,请原谅我.我对Angular 6中的问题感到困惑,我几乎没有输入类型为数字和文本的输入字段,并且我想防止用户输入除'.'以外的任何字符.(点),并且只能输入带有单个点的正数,例如."1.22"而非"1..2."或"-1.12"或"-111".
I am new on Stack overflow so please forgive me If I am wrong anywhere. I am stuck with the problem in Angular 6, I have few input fields of type number and text and I want to prevent users from entering any character other than '.' (dot) and only enter positive numbers with a single dot for eg. "1.22" and not "1..2." or "-1.12" or "-111".
我已经尝试过(keyup),(keypress)和(keydown),但是它们每个对我来说都确实令人困惑.如果有任何指令或解决方案,请提出建议.在html中
I have tried (keyup), (keypress) and (keydown) but each of them works really confusing for me. Please advice if there is any directive or any solution. in html
<input type="number"(keyup)="numberOnlyWithDecimal($event,xyz)" name="weight [(ngModel)]="xyz" min="0" step="0.1">
在.ts
public textlength=0;
numberOnlyWithDecimal(event, text): boolean {
var regex = /^\d+(\.\d+)?$/;
const charCode = (event.which) ? event.which : event.keyCode;
var text2 = text + ''
var test = text2.split(".")
if (text2) {
this.textlength = test.length-1 ;
}
if(text == null && charCode == 46){
return false;
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (!regex.test(charCode)) {
return false
}
if (charCode === 46 && this.textlength ===1 ) {
return false
}
return true;
}
推荐答案
最后,经过大量的头脑风暴,我找到了一个可行的解决方案.我要感谢所有人的帮助,你们是救世主.
Finally, after loads of brainstorming, I have found a working solution for me. I would like to thanks all for helping me, you guys are savior.
我使用了@yanky_cranky代码并对其进行了一些修改,并且适用于数字和文本输入类型.这是代码.
I have used @yanky_cranky code and modified it a little bit and it worked for both number and text input type. Here is the code.
<input type="number" name="weight" appNumbersOnly [(ngModel)]="xyz"/>
指令:
import { Directive, ElementRef, HostListener } from "@angular/core";
@Directive({
selector: '[appNumbersOnly]'
})
export class NumbersOnlyDirective {
public text;
private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
private specialKeys: Array<string> = ['Backspace', 'Tab'];
constructor(private el: ElementRef) {
}
@HostListener('keypress', ['$event'])
onKeyDown(event: KeyboardEvent) {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if(next.includes('.')){
if(this.text == next){
event.preventDefault();
}
this.text= next;
}
if ((next && !String(next).match(this.regex))) {
event.preventDefault();
}
}
}
这篇关于在Angular 6中仅允许带小数的正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!