[英]ng-pattern allows '+' character when regex limits to digits
Am using the regex /^[0-9]+$/ to limit the input of the text box to only accept numbers. 我使用正则表达式/ ^ [0-9] + $ /将文本框的输入限制为仅接受数字。 It's working fine but when the types something like +124 then also it's not setting the text box as invalid.
它工作正常,但是当类似+124的类型时,也不会将文本框设置为无效。
<form name="myForm" novalidate>
<input type="number" ng-model="age" name="age" ng-pattern="/^[0-9]+$/" />
<h3>Valid Status : {{myForm.age.$valid}}</h3>
</form>
Input: 123 Output: myForm.age.$valid - true 输入:123输出:myForm.age。$ valid-true
Input: -123 Output: myForm.age.$valid - false 输入:-123输出:myForm.age。$ valid-假
Input: +123 Output: myForm.age.$valid - true (shouldn't be true) 输入:+123输出:myForm.age。$ valid-true(不应该为true)
https://plnkr.co/edit/3OVE6qiWgJozUb3hyFQ5?p=preview https://plnkr.co/edit/3OVE6qiWgJozUb3hyFQ5?p=preview
If you want to make the pattern work, you need to set the type
attribute to text
. 如果要使模式起作用,则需要将
type
属性设置为text
。 Since you also want to let users type only digits into the input field, add an onkeypress
validation: 由于您还希望用户仅在输入字段中键入数字,因此添加
onkeypress
验证:
<input type="text" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" ng-model="age" name="age" ng-pattern="/^[0-9]+$/" />
Actually, you won't even need the ng-pattern regex then. 实际上,那时您甚至不需要ng-pattern正则表达式。
You can just use: 您可以使用:
ng-pattern="/^[0-9]+$/"
Without setting the input type to number (as default it is text and it should work fine). 无需将输入类型设置为数字(默认情况下为文本,应该可以正常使用)。
Here JSFiddle: https://jsfiddle.net/3ju3b2tu/1/ 这里是JSFiddle: https ://jsfiddle.net/3ju3b2tu/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.