Reputation: 73
Here iam trying to write a regular expression to validate phone no in my own sense. Code is like as follows
$hai = "+458745555---55";
if (!preg_match("/^[\+]{0,1}[0-9\s(\-){0,2}]{6,15}$/", $hai)) {
$valPhone = "Invalid phone number";
} else {
$valPhone = "Valid phone number";
}
echo $valPhone;
Rule:
1.possible to come '+' sign in front of the string
2.only digits,-,space are possible in remaining and - should come in between 0-2
3.maximum length of string excluding '+' would be 6-15
4.We couldn't add space start and end of remaining string excluding '+' sign if it found
but the case of '-' is not working fine for me.Any help would be much appreciated..
Upvotes: 3
Views: 93
Reputation: 29431
This regex does the work:
(?=^\+?[^+]{6,15}$)(?!(?:.*-.*){3,})^\+?\d[\d -]+\d$
Details:
(?=^\+?[^+]{6,15}$)
the whole string is 6 to 15 char long and the +
is optional;(?!(?:.*-.*){3,})
there can't be more than 2 -
;^\+?\d[\d -]+\d$
the string will contains only digit, spaces and -
See demo
Upvotes: 2