Marko Tošić
Marko Tošić

Reputation: 112

Regex in angular- first digit not zero, but allow single zero

I want to have input element which allows one of two conditions:

I wrote this regex (solution works in online regex testers):

/(^0$)|(^[1-9]\d{0,8}$)/

But when I use it in ng-pattern in Angular, it doesn't work. Here is my plunker example:

http://plnkr.co/edit/iDQ7ly8ypJ3UmN5A0hJw?p=preview

Not sure if alternation is doing the problems, or I messed up the regex.

UPDATE: it seems that type="number" is causing problems. Unfortunately, I need to have this in my code, so I'm searching for solution which works with type="number".

Upvotes: 0

Views: 11494

Answers (1)

Millie Smith
Millie Smith

Reputation: 4604

This should work for you. I did the following:

  • Took out the type="number".
  • Gave the form a name.
  • Gave the input a name.
  • Referenced the form and input via their names instead of their id and ng-model values, respectively.

It converts the value to a number under the covers, stripping the leading zeros and converting text to 0, etc.. And the name is the correct way to access it as far as I can tell.

<form name="myForm">
    <input name="myNumberField" ng-model="myNumber" ng-pattern="/(^0$)|(^[1-9]\d{0,8}$)/" required/>
    <span ng-show="myForm.myNumberField.$error.pattern">Invalid pattern</span>
</form>

Here is a plunker for it.

Upvotes: 2

Related Questions