I need a regular expression that works in PHP and JavaScript to validate New Zealand local, mobile and freecall (0800) phone numbers.
Matches: (09)1234567, (021)123456, (021)1234567, (027)123456, 0800 12345, 0800 1234578
Non-Matches: (09)123456 , (021)12345 , (031)1234567, (027)12345 , 0800-1234, 0800123456789
Below is a regular expression I found on the web but it does not seem to work for some reason:
(^([0]\d{1}))(\d{7}$)|(^([0][2]\d{1}))(\d{6,8}$)|([0][8][0][0])([\s])(\d{5,8}$)
Can someone please help with the expression above? Thank you for your help in advance.
UPDATE - I worked it out and the solution is below:
$phone_number = preg_replace('/[^\d\(\)]/', '', $phone_number);
$pattern = '/^(\((03|04|06|07|09)\)\d{7})|(\((021|022|025|027|028|029)\)\d{6,8})|((0508|0800|0900)\d{5,8})$/';
Why all those parentheses and brackets?
^(\(0\d\)\d{7}|\(02\d\)\d{6,8}|0800\s\d{5,8})$
You dont have to wrap everything in pair of parentheses to make it work. That's voodoo programming. For example, ([0][8][0][0])
is simply 0800
.
There's not enough information about the formatting of NZ phone numbers in your question to be sure about this, but a trick may be to first remove all non digit characters and after that test for the number of digits (as far as I can see it should be 9 digits?). Something like:
var phonenr = '(09)1234567'.replace(/[\(\)\s\-]/g,'')
,valid = phonenr.length === 9;
// or check if it's all digits, starting with 0 as well as the length
valid = /^0\d+$/.test(phonenr) && phonenr.length === 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With