30-Oct-2018

Regular Expression For Validating Australian Phone Numbers (Including landline and mobile)

Recently I was tasked with writing a regular expression that would check for a valid Australian phone number for both landline and mobile phone variants whilst allowing for different formats (spaces, no spaces, international dialing code, brackets, area code, no area code).

The below regular expression code and subsequent tests are for Australian mobile and landline numbers only, but could be tweaked to work for other countries as well.

The expression

// This is our bread and butter expression
var phoneExpression = /^\({0,1}((0|\+61)(2|4|3|7|8)){0,1}\){0,1}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{1}(\ |-){0,1}[0-9]{3}$/;

// Valid
var phoneNumber1 = "0411 234 567";
var phoneNumber2 = "(02) 3892 1111";
var phoneNumber3 = "38921111";
var phoneNumber4 = "0411234567";

// Invalid
var phoneNumber5 = "3892 11";
var phoneNumber6 = "diane 0411 234 567";
var phoneNumber7 = "bob";

if (phoneNumber1.match(phoneExpression)) {
console.log('Valid 10 digit mobile number');
}

if (phoneNumber2.match(phoneExpression)) {
console.log('Valid 8 digit landline number with circular brackets wrapping area code');
}

if (phoneNumber3.match(phoneExpression)) {
console.log('Valid 8 digit landline number with no spaces or area code');
}

if (phoneNumber4.match(phoneExpression)) {
console.log('Valid 10 digit mobile number with no spaces or international dialing code');
}

if (!phoneNumber5.match(phoneExpression)) {
console.log('Invalid landline number which is 6 digits instead of 8');
}

if (!phoneNumber6.match(phoneExpression)) {
console.log('A name and space before a valid spaced 10 digit mobile number');
}

if (!phoneNumber7.match(phoneExpression)) {
console.log('No valid number entered, a name appears to have been entered instead');
}

Supported formats: 0411 234 567, +61411 234 567, (02) 3892 1111, 38921111, 3892 111, 02 3892 1111

I haven’t encountered any issues using this expression, but it is possible there could be caveats using this. Like I said, my regular expression-fu isn’t very strong, but it works for what I needed it for and might work for you too.

(from https://ilikekillnerds.com/2014/08/regular-expression-for-validating-australian-phone-numbers-including-landline-and-mobile/, viewed 30-Oct-2018)

Leave a Reply

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram