Angular 5 Validators.pattern 正则表达式仅用于数字 [英] Angular 5 Validators.pattern regex for only numbers

查看:85
本文介绍了Angular 5 Validators.pattern 正则表达式仅用于数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让 Angular 5 Validators.pattern 工作.我已经尝试了所有应该正常工作的正则表达式,但它不起作用.我读到 Validators.pattern 需要不同的格式,但我似乎找不到它...

I'm having trouble getting the Angular 5 Validators.pattern to work. I've tried every regex that SHOULD normally work, but it's not working. I read that Validators.pattern requires a different format, but I can't seem to find it...

任何想法 Validators.pattern 应该是什么

Any ideas what the Validators.pattern should be to

(1) 只允许数字,正负

(1) allow only numbers, positive and negative

(2) 只允许数字,正负,可选择最多 2 个小数位

(2) allow only numbers, positive and negative, optionally with up to 2 decimal places

有效的例子是:11.21.22-21-21.48

Valid examples would be: 1 1.2 1.22 -21 -21.48

任何包含任何字母的内容都是无效的.

Anything with any letter in it would be invalid.

感谢您的帮助!

推荐答案

在尝试了这么多正则表达式之后,没有一个在 Safari 中工作.所以这就是我所做的......

After trying so many regex expressions, none was working in Safari. So here's what I did...

首先,我在创建表单控件时使用了正则表达式:

First, I used the regex when creating the form control:

new FormControl({value: field.value}, [Validators.required, Validators.pattern(/^-?(0|[1-9]\d*)?$/)])

然后,在输入本身中我添加了一个(输入)事件:

Then, in the input itself I added an (input) event:

<input matInput (input)="validateInput(field)" [placeholder]="field.label" type="number" [formControlName]="field.id" [id]="field.id">

那个函数看起来像这样:

And that function looks like this:

validateInput(field) {

    this.detailForm.patchValue({ [field.id]: this.detailForm.controls[field.id].value }); }

}

如果您在 Safari 中输入无效字符(例如 a-z),它不会将其存储在字段控件的值中.它只在那里存储有效值(数字).所以我只是用存储的值修补这个值——如果它是有效的,有数字,就可以了;如果它是无效的,用其他字符,那么它将用空字符串替换输入.

If you enter an invalid character (e.g. a-z) in Safari, it doesn't store it in the field control's value. It only stores valid values (numbers) there. So I'm just patching the value with the stored value -- if it's valid, with numbers, it's fine; if it's invalid, with other characters, then it will replace the input with an empty string.

在所有浏览器上都能完美运行.希望这对某人有所帮助:)

Works perfectly on all browsers. Hope this helps someone :)

这篇关于Angular 5 Validators.pattern 正则表达式仅用于数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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