简体   繁体   English

正则表达式允许为空或1到9位数字

[英]Regular Expression allow null or 1 to 9 digit

I have tried to validate my input quantity field by using pattern attribute. 我试图通过使用模式属性来验证我的输入数量字段。 But my regular expression not working. 但是我的正则表达式不起作用。 Please check 请检查

^(?:[1-9]\d*|)$

Please anyone help me. 请任何人帮助我。 My input field should accept null or 1 to 9 digit. 我的输入字段应接受空值或1到9位数字。 Not accept 0 or any letter and symbol. 不接受0或任何字母和符号。

AngulrJS code: AngulrJS代码:

<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>

If you want to match multiple numbers 1-9 use: 如果要匹配多个1-9使用:

^[1-9]*$

This regex is as good as it gets with regard to checking for NULL values. 在检查NULL值方面,此正则表达式与它一样好。 If you want to also allow nulls, then you should include this logic explicitly in your controller, ie 如果您还希望允许空值,则应在控制器中明确包含此逻辑,即

form.input.$valid || quoteList.quantity === null

Update: 更新:

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. 看来您真正想问的是如何验证以1-9 开头的数字,然后可以跟随任何数字。 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. 同样,您可以在控制器中签入空值,也可以允许它们。

You may check by yourself: 您可以自己检查:

https://regex101.com ^(?:[1-9]\\d*|)$ https://regex101.com ^(?:[1-9] \\ d * |)$

^(?:[1-9]*)$

应该足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM