Angular 2:使用正则表达式进行数字验证 [英] Angular 2: Number validation with Regex

查看:176
本文介绍了Angular 2:使用正则表达式进行数字验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证IE 11中的数字字段.

I'm trying to validate the number field in IE 11.

<input type="number" name="amount" [(ngModel)]="amount" (keypress)="validateNum($event) />

在打字稿中

private validateNum(event: KeyboardEvent): void {
    const pattern = /^\d{1,3}[.]\d{1,6}$/g;
    let inputChar = String.fromCharCode(event.charCode);
    if(!pattern.test(inputChar)) {
        event.preventDefault();
    }
}

在这里,我试图将输入限制为3位数字和5位小数.我面临的问题是,regEx正在为每个按键进行验证(在按下3位数字后无法验证),并且不允许输入任何数字.数字达到限制后,如何验证数字?还是有可能在Angular2中没有regEx的情况下进行验证?我是Angular的新手,需要建议.

Here I'm trying to restrict the input to 3 digits and 5 decimals. The problem I'm facing is, regEx is validating for each key pressed (Not validating after the 3 digits pressed) and it is not allowing to enter any number. How do I validate the number after the numbers reach the restriction? Or is it possible to validate without regEx in Angular2?? I'm new to Angular and need suggestion.

推荐答案

有一个很棒的库,叫做

There's an awesome library called text-mask. You can easily create a mask and restrict your user to input 3 digits and 5 decimals.

mask = [/\d/, /\d/,/\d/, '.', /\d/, /\d/, /\d/, /\d/, /\d/]

这篇关于Angular 2:使用正则表达式进行数字验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆