Variable length for input field


Im using an angular 1 app.
I have this field:

<input type="string" maxlength="4" ng-model="account.myNumber" />

This field should only accept integers. I think that if I use “type=number” some browser will display the field in a strange way with some kind of selectbox to change the numbers in the field. So I think it’s best to have a regex to only allow numbers.
However, this field has a maxlength of 4 characters ONLY IF the first character is not equal to 0.
If the first entered character is 0, then the maxlength should be 5.
What I wonder if there is some regex to solve this. Or should I let the controller check this? I think it would be neater with a regex if it is possible to let it calculate that.


a regex would be something like this /^0?[0-9]{4}$/, but there are maybe expectations that you didn’t formulate because you considered them as evident
Mm it is not working. I can enter letters and there is no limit for number of chars: <input type=”string” name=”noname” ng-pattern=”/^0?[0-9]{4}$/” >
– oderfla
1 hour ago
my bad, the previous regex will work if this is the exact number of elements, not for maximum. And if you use it with ng-pattern, you have to remove the /, ^ and $ which are added automatically. Try with 0?[0-9]{0,4}
^0[0-9]{4}|(?!0)[0-9]{4}$ this regex can help you with what you need.
I think this question has been answered <a href=”Tags:, ,