Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for Australian phone number validation

I tried below regex for phone numbers validation but did not work properly,

^([+61|0](2|4|3|7|8|)){0,2}([ 0-9]|[(]){2,3}([)]|[0-9]){6}([ ])[0-9]{7,20}$

Here are examples I expect to pass validation

+61(02)89876544
+61 2 8986 6544
02 8986 6544
+61289876544
0414 570776 
0414570776
0414 570 776
+61 414 570776
+61 (0)414 570776

below characters also be accepted. ()-+ space

like image 220
KRR Avatar asked Oct 12 '16 03:10

KRR


People also ask

How do I validate a pattern in RegEx?

How to add RegEx validation? RegEx pattern validation can be added to text input type questions. To add validation, click on the Validation icon on the text input type question.

What is RegEx in validation?

What is RegEx Validation (Regular Expression)? RegEx validation is essentially a syntax check which makes it possible to see whether an email address is spelled correctly, has no spaces, commas, and all the @s, dots and domain extensions are in the right place.

How do I find RegEx numbers?

Regex to match 10 digit Phone number with Country Code Prefix. String countryCodeRegex = "^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .] ? \\d{3}[- .]


2 Answers

That's quite the phone number structure. The easiest solution is to ask the user to input in a particular format or have the the form automatically format it. If you must use a regex, this is what I came up with:

^(?:\+?(61))? ?(?:\((?=.*\)))?(0?[2-57-8])\)? ?(\d\d(?:[- ](?=\d{3})|(?!\d\d[- ]?\d[- ]))\d\d[- ]?\d[- ]?\d{3})$

Capture groups:

  1. Country Code (optional)
  2. Area/Provider Code (optional)
  3. The Phone Number

Demo: https://regex101.com/r/dkFASs/6

This was what I used to nail down the format: https://en.wikipedia.org/wiki/Telephone_numbers_in_Australia

When tackling a larger regex like this, I find the esiest way is to stick your test cases into a tool like regex101.com and then go capture group by capture group (naming them if you can) until you get to the end. As soon as one group doesn't match, change what you already have until it does.

Edit 2019: Since this question still gets attention occasionally, I wanted to note that it might be better to use a validation library if possible. My suggestion would be Google's i18n library for phone numbers. It's much more robust than a regex could ever be.

like image 149
3ocene Avatar answered Oct 23 '22 04:10

3ocene


try this

\b([\+-]?\d{2}|\d{4})\s*\(?\d+\)?\s*(?:\d+\s*)+\b
like image 44
bad_boy Avatar answered Oct 23 '22 04:10

bad_boy