2

How do i do an input validation for NRIC numbers where there are both numbers and alphabets? Example of NRIC number: S9738275G, S8937231H, S7402343B ic=input('Enter NRIC Number: ')

Edwin Chew
  • 29
  • 3
  • `re.match(r"[\dA-Z]+")` should work. – Rohit Jain Jul 31 '16 at 14:47
  • FWIW, I wrote a function yesterday that determines the NRIC check code. http://stackoverflow.com/a/38674235/4014959 – PM 2Ring Jul 31 '16 at 15:13
  • Wikipedia has [Information about the Structure of the NRIC number](https://en.wikipedia.org/wiki/National_Registration_Identity_Card#Structure_of_the_NRIC_number.2FFIN) – PM 2Ring Jul 31 '16 at 15:16

3 Answers3

1

For your use case this should be enough:

>>> a = 'A12345678B'
>>> if a[0].isalpha() and a[-1].isalpha() and a[1:-1].isdigit(): print True
... 
True
>>> a = 'A12345678'
>>> if a[0].isalpha() and a[-1].isalpha() and a[1:-1].isdigit(): print True
... 
>>> 

[0] first character, [-1] last character, [1:-1] second character to last but one character

Edit: Looking at PM 2Ring's comment, the NRIC number has a specific structure and specific method of creating the check digit/character, so I'd follow the code given in the link provided. Assuming that your NRIC number is the same obviously, as you didn't specify what it was.
Intriguingly: "The algorithm to calculate the checksum of the NRIC is not publicly available" Wikipedia

Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60
0

This can be done in a lot of different ways. Depending on the scale of your application, you might want something simpler or more complex.

If you want something rock solid, you can use a library such as Pygood for that.

If you're looking for something in the middle, you can also use regex, see here an example.

If you want to keep it as simple as possible, you can do a simple validation like so:

str = "B123"
if str[0].isalpha() and not str[1:].isalpha():
    # is valid
Community
  • 1
  • 1
David Gomes
  • 5,644
  • 16
  • 60
  • 103
  • How about the number of alphabets and numerics needed to input? In this case it would be 9 as ' S9738275G' has 9 alphanumeric. – Edwin Chew Jul 31 '16 at 14:58
0

Try this

string = 'S9738275G';

if string.isalnum():
    print('It\'s alphanumeric string')
else:
    print('It\'s not an alphanumeric string')
Rohit Khatri
  • 1,980
  • 3
  • 25
  • 45