问题描述
我试图通过使用模式属性来验证我的输入数量字段.但是我的正则表达式不起作用.请检查
I have tried to validate my input quantity field by using pattern attribute. But my regular expression not working. Please check
^(?:[1-9]\d*|)$
请任何人帮助我.我的输入字段应接受空值或1到9位数字.不接受0或任何字母和符号.
Please anyone help me. My input field should accept null or 1 to 9 digit. Not accept 0 or any letter and symbol.
AngulrJS代码:
AngulrJS code:
<input class="form-control" name="quantity" ng-model="quoteList.quantity" placeholder="Quantity" required="" min="1" ng-pattern="/^(?:[1-9]\d*|)$/">
<div ng-show="userForm.$submitted || userForm.quantity.$touched">
<span ng-show="userForm.quantity.$error.pattern" class="text-danger">Not valid number!</span>
</div>
推荐答案
如果要匹配多个数字1-9
,请使用:
If you want to match multiple numbers 1-9
use:
^[1-9]*$
此正则表达式与检查NULL
值一样好.如果您还希望允许空值,则应在控制器中明确包含此逻辑,即
This regex is as good as it gets with regard to checking for NULL
values. If you want to also allow nulls, then you should include this logic explicitly in your controller, i.e.
form.input.$valid || quoteList.quantity === null
更新:
您似乎真正想问的是如何用1-9
验证开头的数字,但是后面可以跟任何数字.如果是这样,请尝试使用此正则表达式:
It appears that what you really wanted to ask is how to validate a number which begins with 1-9
, but then can be followed by any digit. If so, then try this regex:
^[1-9][0-9]*$
同样,您可以在控制器中签入空值,也可以允许它们.
Again, you can check in your controller for null values and also allow them too.
这篇关于正则表达式允许为空或1到9位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!