Chinmay235 Chinmay235 - 1 month ago 13
AngularJS Question

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. Not accept 0 or any letter and symbol.

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>

Answer

If you want to match multiple numbers 1-9 use:

^[1-9]*$

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