[英]Only allow positive numbers with only one decimal in Angular 6
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 '.'
我在 Angular 6 中遇到了这个问题,我的数字和文本类型的输入字段很少,我想阻止用户输入除 '.' 以外的任何字符。 (dot) and only enter positive numbers with a single dot for eg.
(dot) 并且只输入带一个点的正数,例如。 "1.22" and not "1..2."
“1.22”而不是“1..2” or "-1.12" or "-111".
或“-1.12”或“-111”。
I have tried (keyup), (keypress) and (keydown) but each of them works really confusing for me.我已经尝试过 (keyup)、(keypress) 和 (keydown) 但它们中的每一个都让我感到困惑。 Please advice if there is any directive or any solution.
如果有任何指令或任何解决方案,请告知。 in html
在 html 中
<input type="number"(keyup)="numberOnlyWithDecimal($event,xyz)" name="weight [(ngModel)]="xyz" min="0" step="0.1">
in .ts在.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;
} }
Here you go, complete working solution for you :在这里,为您提供完整的工作解决方案:
1) Directive 1) 指令
@Directive({
selector: '[appNumbersOnly]'
})
export class NumbersOnlyDirective {
private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
private specialKeys: Array<string> = ['Backspace', 'Tab'];
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$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 && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
2) Usage in html 2) 在 html 中的使用
<input type="text" name="weight" appNumbersOnly [(ngModel)]="xyz" />
Stackblitz here for reference Stackblitz在这里供参考
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.
我要感谢所有帮助我的人,你们是救世主。
I have used @yanky_cranky code and modified it a little bit and it worked for both number and text input type.我使用了@yanky_cranky 代码并对其进行了一些修改,它适用于数字和文本输入类型。 Here is the code.
这是代码。
<input type="number" name="weight" appNumbersOnly [(ngModel)]="xyz"/>
Directive:指示:
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();
}
}
}
you can create your custom directive您可以创建自定义指令
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimaNumberDirective {
private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-'];
@Input('appTwoDigitDecimaNumber') decimal:any;
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if(this.decimal){
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}else{
const charCode = (event.which) ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 105)) {
event.preventDefault();
}
return;
}
}
Usage用法
<input type="text" [appTwoDigitDecimaNumber]="true">
I hope it will help you a lot.我希望它会帮助你很多。
Note : you can use it any number
type field where you want use just add [appTwoDigitDecimaNumber]="true"
if you dont want to use then add [appTwoDigitDecimaNumber]="false"
.注意:您可以在任何您想要使用的
number
类型字段中使用它,只需添加[appTwoDigitDecimaNumber]="true"
如果您不想使用然后添加[appTwoDigitDecimaNumber]="false"
。 Bacause i have use these directive in dynamic forms that why i have set it base on true
or false
.因为我以动态形式使用了这些指令,所以我将它设置为基于
true
或false
。 You can use it in Dynamic form
also您也可以以
Dynamic form
使用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.