Regex for Passport Number
28,615
Solution 1
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)
Solution 2
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
}
}
Comments
-
Dinny about 4 years
I am trying to implement regex validation for passport number.
My requirement is
- Length should be minimum 3 characters to a maximum of 20 characters.
- 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.