Pallavi February 2016

What is the regular expression for zip code i.e. 96754-2222

 <input class="input-width" placeholder="XXXXX" maxlength="10"
  type="text" name="zip" ng-model="shipping.zip" required ng-pattern="/^[0-9]+$/" />

This is entering only numbers.how will I enter 5 numbers then '-' then 4 numbers. I am new to regular expressions. Can anyone help me in this to create this one.

Answers


mmm February 2016

You can use

pattern = "/^\d{5}-\d{4}$/"

\d is equally to [0-9] - matching every digit


Jon Surrell February 2016

This matches your requirements:

^[0-9]{5}(?:-[0-9]{4})?$

That is:

 characters 0-9
  |    5 of them 
  |    |
  v    v
^[0-9]{5}(?:-[0-9]{4})?$
         ^^^          ^ 
          |           | 
          |           group is optional
          |
group (no-capture)

See annotations. Also there is a literal - dash and ^ and $ anchor at the beginning and end of string.

5 digits followed by optional - and 4 digits.

Post Status

Asked in February 2016
Viewed 3,014 times
Voted 8
Answered 2 times

Search




Leave an answer