-1

I'm new to programming. How should a regular expression look like, to match the following requirements:

  • String has to start with "+"

  • After that + only numbers and blanks in any combination are allowed

Example for a valid number: +49 1223 3447 554 9

I'm trying to validate a String telephone field with Java Script.

Thanks!

user3335966
  • 2,673
  • 4
  • 30
  • 33
M. Bru
  • 1
  • 2
    possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – ndnenkov Aug 16 '15 at 12:15

2 Answers2

0
function checkPhone(str) {
  return str.match(/^\+[0-9\s]+/) ? true : false;
};

var phone = "+49 1223 3447 554 9";
console.log('checkPhone', phone, checkPhone(phone));

even if this regexp satisfy your request, I don't think it's enough to validate phone number, it should be at least 5 digits without counting spaces, check the link provided by @ndn

Simone Sanfratello
  • 1,520
  • 1
  • 10
  • 21
  • Thanks for your help. Works perfectly for checking the starting + sign. Although you can save numbers that have other characters than numbers in it. For example +43 5a522 25&32 validates as a correct number. After the plus sign only numbers and blanks should be possible. – M. Bru Aug 17 '15 at 07:25
0

For validation of phone I use either feature

function isValidPhone(sendersPhone) {
    var pattern = new RegExp(/\d\(\d{3}\)-\d{3}-\d{2}-\d{2}/);
    return pattern.test(sendersPhone);
}

Or if you are using jquery, it is often more convenient to use the mask, for example Masked Input Plugin for jQuery https://github.com/digitalBush/jquery.maskedinput Or for angular.js - angular ui-mask (https://github.com/angular-ui/ui-mask)

Alexey Popov
  • 76
  • 2
  • 8