Angular 5 Validators.pattern正则表达式仅用于数字 [英] Angular 5 Validators.pattern regex for only numbers
问题描述
我无法使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) allow only numbers, positive and negative, optionally with up to 2 decimal places
有效的例子是: 1个 1.2 1.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屋!