Regular Expression checking for Malaysia mobile no.

Malaysia mobile no is in format 601XXXXXXXX (You can find more details from http://www.skmm.gov.my/)

I start learning regular rexpression when I want to do mobile no. validation, basically just refer to two pages, Regular Expression CheatSheet and Regular Expression Tester, a very useful resources to me.

Below is my RegExp test code for mobileNo validation:

^6?01\d{8}$

Let go through the code (Refer to Regular Expression CheatSheet):

  1. This reg. exp. only accept format in (601AAAAAAAA) or (01AAAAAAAA), A is digit from 0 ~ 9.
  2. ‘^601’ indicates that mobile number must start with ‘601’.
  3. Since I want to allow mobile no. in format (01AAAAAAAA), so add a ‘?’ after ‘^6’, it become like this ‘^6?01’. ‘?’ means there is no matching of previous expression or maximum one matching of previous expression, ‘6’ is the one.
  4. In (601AAAAAAAA), notice that A x 8, so the regexp follow by ‘\d{8}’, ‘\d’ match any decimal digit, ‘{8}’ says that any eight decimal digit after that will be match. So the test code is ‘^6?01\d{8}’.
  5. Yeah the story end. ‘^6?01\d{8}’ will be the final code for my validation.
  6. After some time, I found the number ‘60191234567999999’ can pass my validation, oops~~, need to fix the checking.
  7. After browses some regexp example, ‘$’ is found to prevent above error (previously I do not know what is that ‘$’ serve for).
  8. The ‘$’ will make sure ONLY eight decimal digit in the mobile no., so now ‘60191234567999999’ wouldn’t pass my test since there are 13 digits after ‘6019’, but ‘60191234567’ will pass the test.
  9. Ok, story end again.

Anybody has better test code are welcome. 🙂

Reference:

  1. http://regexlib.com/CheatSheet.aspx
  2. http://regexlib.com/RETester.aspx
  3. http://regexlib.com/DisplayPatterns.aspx (Regexp examples)
Advertisements