Indian pincode validation regex - Only six digits, shouldn't start with `0`

55,226

The problem with ^[1-9][0-9]{6}*$ is it is an invalid regex because of {6}* and ^([^0][0-9]){6}$ is that it is allowing any character that is not 0 followed by six digits.

Use

^[1-9][0-9]{5}$

Explanation:

  1. ^: Starts with anchor
  2. [1-9]: Matches exactly one digit from 1 to 9
  3. [0-9]{5}: Matches exactly five digits in the inclusive range 0-9
  4. $: Ends with anchor

Regex Visualization

Regex101 Playground

HTML5 Demo:

input:invalid {
  color: red;
}
<input type="text" pattern="[1-9][0-9]{5}" />
Share:
55,226
Some Java Guy
Author by

Some Java Guy

I did Java/J2EE for long time, now AWS architecture.

Updated on August 23, 2022

Comments

  • Some Java Guy
    Some Java Guy almost 2 years

    I have tried Regex accept numeric only. First character can't be 0 and What is the regex for "Any positive integer, excluding 0" however that didn't work as per my requirements.

    I want exact 6 digit numeric number but shouldn't start with 0

    I've tried

    ^[1-9][0-9]{6}*$
    ^([^0][0-9]){6}$
    ...
    

    Need fine tuning.

  • Amit
    Amit over 8 years
    The problem with ^[1-9][0-9]{6}*$ is that it's an invalid regex
  • Tushar
    Tushar over 4 years
    {1} can be removed. You can write \s{0,1} as \s?.
  • Kavvya Ramarathnam
    Kavvya Ramarathnam about 3 years
    yeah {1} can be removed. but if you remove \s{0,1} , The space will be taken as mandatory