0

Possible Duplicate:
A comprehensive regex for phone number validation
Regular Expression for matching a phone number

I need a regular expression to validate phone numbers. The conditions are:
(i) min 7 digits and max 15 digits.
(ii) Possible valid values are

111111 or 111-1111 or 111-1111 ch 111.

Please help me reach a solution.

Community
  • 1
  • 1
sathish
  • 800
  • 1
  • 8
  • 19
  • what u have tried so far??? have u google it – xkeshav Jan 17 '12 at 12:06
  • ch 111 - it may have string with couple of words and then continue with digits. – sathish Jan 17 '12 at 12:09
  • 2
    your first *possible value* has 6 digits – gion_13 Jan 17 '12 at 12:09
  • 1
    possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/), [Regular Expression for matching a phone number](http://stackoverflow.com/questions/4395058/), [Regular Expression for matching a phone number](http://stackoverflow.com/questions/3256547). [What is this for](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? A regex may not be the best solution. – outis Jan 17 '12 at 12:11
  • There is also [regular expression library](http://regexlib.com/DisplayPatterns.aspx?categoryId=7&cattabindex=6&AspxAutoDetectCookieSupport=1) available. Just copy/paste the right regex. – Janis Veinbergs Jan 17 '12 at 12:15

2 Answers2

3
preg_match('/^(\D*\d){7,15}\D*$/', $subject)

ensures that subject contains 7 to 15 digits, and doesn't care about anything else.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • +1. A little note: the question is about PHP, not Javascript :) – J0HN Jan 17 '12 at 12:31
  • @J0HN: Thanks - there was a jquery tag when I answered; I completely missed the php tag... – Tim Pietzcker Jan 17 '12 at 12:35
  • fine, but if have input like '111--111111', it should not be valid. But the expression returns true.. – sathish Jan 17 '12 at 13:20
  • @sathish: Then you must specify *exactly* what your allowed input forms are (and do this in your question, not as an answer to this comment). Your comment from above "it may have string with couple of words and the continue with digits" is highly unspecific. – Tim Pietzcker Jan 17 '12 at 13:22
1

use this code to check is it phone:

function isValidPhoneNumber(phoneNumber) {
var pattern = new RegExp(/^\+?(\d[\d\+\(\) ]{5,}\d$)/);
return pattern.test(phoneNumber);
};

on your keyup or blur your input, call this function:

function validatePhone() {
var phone = $("input#phone").val();
if (!isValidPhoneNumber(phone)) {
    return false;
} else {
    return phone;
}
};
Ali U
  • 384
  • 5
  • 17