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

4

11

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.

Swadeshi answered 23/11, 2015 at 7:17 Comment(0)
P
51

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}" />
Pigweed answered 23/11, 2015 at 7:19 Comment(1)
The problem with ^[1-9][0-9]{6}*$ is that it's an invalid regexColombi
C
3

This regular expression covers;

  1. PIN code doesn't start from zero

  2. Allows 6 digits only

  3. Allows 6 consecutive digits (e.g. 431602)

  4. Allows 1 space after 3 digits (e.g. 431 602)

([1-9]{1}[0-9]{5}|[1-9]{1}[0-9]{3}\\s[0-9]{3})
Catwalk answered 19/5, 2020 at 11:46 Comment(0)
H
0

Some websites and banks have the habit of spacing pincode after 3 digits. To match both 515411 and 515 411 the following pattern will help.

^[1-9]{1}[0-9]{2}\s{0,1}[0-9]{3}$
  • ^[1-9]{1} - PIN Code that starts with digits 1-9
  • [0-9]{2} - Next two digits may range from 0-9
  • \s{0,1} - Space that can occur once or never
  • [0-9]{3}$ - Last 3 needs to be digits ranging from 0-9
Horseradish answered 25/8, 2019 at 7:6 Comment(2)
{1} can be removed. You can write \s{0,1} as \s?.Pigweed
yeah {1} can be removed. but if you remove \s{0,1} , The space will be taken as mandatoryLombardi
M
0

input:invalid {
  color: red;
}
<input type="text" pattern="[1-9][0-9]{5}" />
Marchioness answered 6/7 at 4:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.