Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]))? ?(dd(?:[- ](?=d{3})|(?!dd[- ]?d[- ]))dd[- ]?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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...