4

I would like to check, if a text contains a telephone number or not.

Regex = /\d{6,}/; 

This would check for 6 digits in a row, but phone numbers can also contain space, +, (, ), -, . and slash...

How would I check against any kind of telephone number?

I would like to detect numbers in these forms:

+49 123 456789
0049 123456789
(040) 132 45 67
040/123 456
040-132-12
040 123456
+49 (0)40-123456
rubo77
  • 19,527
  • 31
  • 134
  • 226
  • 1
    This may help: http://stackoverflow.com/questions/6195458/phone-number-validation-javascript There are probably a handful of other solutions on this site somewhere. – Wiseguy Apr 27 '13 at 23:21
  • Where I live, mobile numbers are 10 digits, usually presented in a blocks of 4, 3, 3 digits separated by spaces. Fixed line phones are 8 digits in two blocks of 4 and may or may not have a two digit area code, usually presented in brackets. Other places have different formats. – RobG Apr 28 '13 at 02:47

2 Answers2

1

This would be impossible not be feasible. There are simply too many different lengths and formats of phone numbers all over the world. You should instead focus on a certain subset of formats/lengths that you are willing to accept.

If that still leaves you with too many options, you might need to just go for a simple check like this:

  • non-null
  • Includes only these characters:
    • 0-9
    • +
    • [space]
Lix
  • 47,311
  • 12
  • 103
  • 131
1

It is not 100% possible to serve all cases, and you probably have to adapt it to your needs, but for example this regular expression will do the job:

var Regex = /\b[\+]?[(]?[0-9]{2,6}[)]?[-\s\.]?[-\s\/\.0-9]{3,15}\b/m;  

Here is an example how it works:

function check_for_phone(){
    
      var message = document.getElementById("a").value;
      var Regex = /\b[\+]?[(]?[0-9]{2,6}[)]?[-\s\.]?[-\s\/\.0-9]{3,15}\b/m; 
       
      alert( Regex.test(message) ); 
      // This will alert 'true' if the textarea contains a phonenumber 
}
<textarea id="a">please call me: 040 12345</textarea>
<input type="button" onclick="check_for_phone()"  value="check for telephone">

found here: https://stackoverflow.com/a/29767609/1069083

rubo77
  • 19,527
  • 31
  • 134
  • 226