Regex for Passport Number
Asked Answered
J

3

8

I am trying to implement regex validation for passport number.

My requirement is

  1. Length should be minimum 3 characters to a maximum of 20 characters.
  2. Should not be only 0's

I tried with the below regular expression

^(?!0{3,20})[a-zA-Z0-9]{3,20}$

This seems to work for most of the cases, but incase my text contains 3 or more leading zeros, it seems to fail. Such as '00000001'.

Example Matches

  • 101AE24 - Working as expected
  • 00 - Not working as expected
  • 01234 - Working as expected
  • 00001 - Not working (But it should also be match)

Any help would be much appreciated.

Jam answered 17/11, 2016 at 6:2 Comment(4)
Does it have to be a regex? You could solve this by first checking the length, then making sure you had at least 1 or more of the following [A-Za-z1-9]Gillie
for length ^[0-9]{3,20}$ and then check Convet.ToInt32(value) == 0Risibility
@viveknuna String can have alpha chars.Gillie
then use [a-zA-Z0-9] simple and int.TryParseRisibility
R
14

What about this?

^(?!^0+$)[a-zA-Z0-9]{3,20}$

Instead of saying 'reject values with 3-20 zeros', we can just say 'reject anything that only contains zeros (regardless of the length, since <3 and >20 fail anyway)

Redoubtable answered 17/11, 2016 at 6:9 Comment(1)
Hello I want to validate passport numbers for all countries. And I want to have a list of regex for every country, Something like this: github.com/validatorjs/validator.js/blob/master/src/lib/… But it is not complete. do you have a complete list?Scabrous
G
1

It took me around 5 minutes to learn Regex online [iOS, Swift]. Here is my a simple answer to understand for beginners.

For 1 Alphabet & 7 digits:

[A-Z]{1}[0-9]{7}

For 2 Alphabets & 7 digits:

[A-Z]{2}[0-9]{7}

--

func validatePassport(from value: String?) throws {
    guard let passportNo = value, !passportNo.isEmpty else {
        throw MyError.noPassport
    }
    let PASSPORT_REG_EX = "[A-Z]{1}[0-9]{7}"
    let passport = NSPredicate(format:"SELF MATCHES %@", PASSPORT_REG_EX)

    if !passport.evaluate(with: passportNo) {
        throw MyError.invalidPassport
    }
}
Graduated answered 13/2, 2020 at 6:3 Comment(1)
The passport number can also be numeric only, for example, mine contains 8 numbers. The pattern which is quite good is ^(?!(0))[a-zA-Z0-9]{6,9}$ - cannot start with 0, and contains 6-9 alphanumeric characters. I however believe that there can only be 1 or 2 letter at the beginning which would make it an even more complex pattern.Halyard
A
1

I saw this expression from this link

^[A-Z0-9<]{9}[0-9]{1}[A-Z]{3}[0-9]{7}[A-Z]{1}[0-9]{7}[A-Z0-9<]{14}[0-9]{2}$
Arnuad answered 5/5, 2020 at 12:30 Comment(1)
This regex is valid for Sri Lankan passports.Brahmana

© 2022 - 2024 — McMap. All rights reserved.