jenryb
jenryb

Reputation: 2117

Using ng-pattern to recognize leading zero in Angular alphanumeric field

How can I recognize a leading zero in an alphanumeric field using ng-pattern in angular?

  <body ng-app>
    <h1>Regex test</h1>
    <form name="myForm">
      <input name="myNumberField" ng-model="myNumber" ng-pattern="REGEX HERE" required/>
      <span ng-show="myForm.myNumberField.$error.pattern">Invalid pattern</span>
    </form>
  </body>

I tried ng-pattern="/(^0[0-9].*$)/" and ng-pattern="/(^0.*$)/"

Here is a plunker: http://plnkr.co/edit/laB3Q7nApuoLT9NYnCGX?p=preview

For example:

Invalid Patterns:

0AHFFB

00AJFH

0038429347

Valid Patterns:

AHFFB

AJFBN

32400342

30292900

Upvotes: 0

Views: 1146

Answers (3)

jenryb
jenryb

Reputation: 2117

ng-pattern="/(^[a-zA-Z1-9][a-zA-Z0-9]*$)/"

Works for me.

Upvotes: 1

neojg
neojg

Reputation: 221

You may use the expression:

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

It reads:

  • start from the beginning of the string
  • accept a character that is either a word character \w or 1 to 9
  • accept any number of word characters or digits (including 0)
  • end of string

Test it on https://regex101.com/

Upvotes: 0

Tanvi B
Tanvi B

Reputation: 1567

Can you try below

^[1-9][0-9]*$

Upvotes: 0

Related Questions