SitePoint Sponsor

User Tag List

Results 1 to 9 of 9

Thread: Phone Number Validation

  1. #1
    SitePoint Member
    Join Date
    Apr 2009
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Phone Number Validation

    Hi,

    I am looking for a javascript / jQuery code for phone number validation if the phone number has all 0’s in it.

    If the value entered is only zeros, it should display the “Enter a valid value” message.

    I want to prohibit 0, 00, 000000, 000-000-0000, 000.000.0000, etc. ( All possible phone number formats )

    Can anyone help me in it?

    Thanks,
    Devesh

  2. #2
    Unobtrusively zen silver trophybronze trophy
    SitePoint Award Recipient paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,233
    Mentioned
    42 Post(s)
    Tagged
    2 Thread(s)
    The following is the jQuery validator for US-phone validation

    Code javascript:
    jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
        phone_number = phone_number.replace(/\s+/g, ""); 
    	return this.optional(element) || phone_number.length > 9 &&
    		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
    }, "Please specify a valid phone number");
     
    $("#myform").validate({
      rules: {
        field: {
          required: true,
          phoneUS: true
        }
      }
    });
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Member
    Join Date
    Apr 2009
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks friend,

    But I need it for standard international format, mostly for EU countries.

    Can you help me?

    Please go through the below mentioned code and let me know if you can modify it to my requirements -

    Thanks.



    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Javascript Phone Number Validation </title>

    <script language = "Javascript" type="text/javascript">

    // Declaring required variables
    var digits = "0123456789";
    // non-digit characters which are allowed in phone numbers
    var phoneNumberDelimiters = "()-,. ";
    // characters which are allowed in international phone numbers
    // (a leading + is OK)
    var validWorldPhoneChars = phoneNumberDelimiters + "+";
    // Minimum no of digits in an international phone no.
    var minDigitsInIPhoneNumber = 11;

    function isInteger(s)
    { var i;
    for (i = 0; i < s.length; i++)
    {
    // Check that current character is number.
    var c = s.charAt(i);
    if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
    }
    function trim(s)
    { var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {
    // Check that current character isn't whitespace.
    var c = s.charAt(i);
    if (c != " ") returnString += c;
    }
    return returnString;
    }
    function stripCharsInBag(s, bag)
    { var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {
    // Check that current character isn't whitespace.
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
    }

    function checkInternationalPhone(strPhone){
    var bracket=3
    strPhone=trim(strPhone)
    if(strPhone.indexOf("+")>1) return false
    if(strPhone.indexOf("-")!=-1)bracket=bracket+1
    if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
    var brchr=strPhone.indexOf("(")
    if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
    if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
    s=stripCharsInBag(strPhone,validWorldPhoneChars);
    return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
    }

    function ValidatePhoneNumber(){
    var Phone=document.frmSample.txtPhone

    if (checkInternationalPhone(Phone.value)==false){
    alert("Please Enter a Valid Phone Number")
    Phone.value=""
    Phone.focus()
    return false
    }
    return true
    }
    </script>

    </head>

    <body>
    <form name="frmSample" method="post" action="#" onSubmit="return ValidatePhoneNumber()">
    <p>Enter a phone number :
    <input type="text" name="txtPhone">
    </p>
    <p>
    <input type="submit" name="Submit" value="Submit">
    </p>
    </form>
    </body>
    </html>

  4. #4
    Unobtrusively zen silver trophybronze trophy
    SitePoint Award Recipient paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,233
    Mentioned
    42 Post(s)
    Tagged
    2 Thread(s)
    Well, do you see the regular expression?

    Code:
    /^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/
    That means:
    • ^ this is the start of the number
    • (1-?)? an optional non-zero digit
    • [2-9]\d{2} 3-digits from 200 upwards
    • (/(...\)|...) optional parenthesis for area code
    • -? optional divider
    • [2-9]\d{2} 3-digits from 200 upwards
    • -? optional divider
    • \d{4} four more digits
    • $ end of the number


    When you figure out what formats are acceptable and which are not, we can craft together a regular expression for you that will make matching them a breeze.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    15,862
    Mentioned
    8 Post(s)
    Tagged
    1 Thread(s)
    If you want to accept phone numbers from anywhere at all then there are not very many restrictions you can apply to them as different countries use different formats. There are even a few valid phone numbers that consist of nothing but zeros.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  6. #6
    From space with love SitePoint Award Recipient SpacePhoenix's Avatar
    Join Date
    May 2007
    Location
    Poole, UK
    Posts
    4,298
    Mentioned
    55 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by felgall View Post
    If you want to accept phone numbers from anywhere at all then there are not very many restrictions you can apply to them as different countries use different formats. There are even a few valid phone numbers that consist of nothing but zeros.
    You can also get different formats within the same country (take the UK for example).
    Community Team Advisor
    Forum Guidelines: Posting FAQ Signatures FAQ Self Promotion FAQ
    Help the Mods: What's Fluff? Report Fluff/Spam to a Moderator

  7. #7
    SitePoint Member
    Join Date
    Apr 2009
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks all for the suggestions.

    I have completed the phone no. validation code.

    Some features are -

    1. The validation will take place only if all the digits in the phone number are “0”. Whether it is one time or more ( maximum 16 digits ).
    2. It will also take care of the delimiters – “+-(),. ”. These delimiters are common in any phone number.
    3. Validation will only allow occurrences of the numbers [0-9] and the delimiters mentioned above, in the phone number. It will not allow occurrences of all 0’s and other special characters.
    4. The validation code is applicable to all types for phone number standards (maximum 16 digits ).

    The code is -

    Code HTML4Strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    	<head>
    	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    	<title>Validation Test</title>
    		<script type="text/javascript" language="javascript">
     
    		var ValidChars = "0123456789";
    		var phoneNumberDelimiters = "()-,.+ ";
    		var IsNumber=true;
    		var Char;		
     
    		function trim(strPhone)
    		{   var i;
    			var returnString = "";
    			// Search through string's characters one by one.
    			// If character is not a whitespace, append to returnString.
    			for (i = 0; i < strPhone.length; i++)
    			{   
    				// Check that current character isn't whitespace.
    				var c = strPhone.charAt(i);
    				if (c != " ") returnString += c;
    			}
    			return returnString;
    		}
     
    		function stripCharsInBag(strPhone, phoneNumberDelimiters){
    			var i;
    			var returnString = "";
    			// Search through string's characters one by one.
    			// If character is not in phoneNumberDelimiters, append to returnString.
    			for (i = 0; i < strPhone.length; i++)
    			{   
    				// Check that current character isn't whitespace.
    				var c = strPhone.charAt(i);
    				if (phoneNumberDelimiters.indexOf(c) == -1) returnString += c;
    			}
    			return returnString;
    		}
     
    		function IsNumeric(strPhone){		
    			for (i = 0; i < strPhone.length && IsNumber == true; i++) 
    			{ 
    				Char = strPhone.charAt(i);
    				if (strPhone == "0" || strPhone == "00" || strPhone == "000" || strPhone == "0000" || strPhone == "00000" || strPhone == "000000" || strPhone == "0000000" || strPhone == "00000000" || strPhone == "000000000" || strPhone == "0000000000" || strPhone == "00000000000" || strPhone == "000000000000" || strPhone == "0000000000000" || strPhone == "00000000000000" || strPhone == "000000000000000" || strPhone == "0000000000000000") return false; 
    				if (ValidChars.indexOf(Char) == -1) 
    				{
    					IsNumber = false;
    				}
    			}
    			return IsNumber;		
    		}
     
    		function checkInternationalPhone(strPhone){		
    			strPhone=trim(strPhone);
    			strPhone=stripCharsInBag(strPhone, phoneNumberDelimiters);
    			return (IsNumeric(strPhone));
    		}
     
    		function ValidatePhoneNumber(){
    			var Phone=document.frmSample.txtPhone;
     
    			if (checkInternationalPhone(Phone.value)==false){
    				alert("Please Enter a Valid Phone Number");
    				Phone.value="";
    				Phone.focus();
    				return false;
    			}
    			return true;
    		 }
    		</script>
    	</head>	
    	<body>
    		<form name="frmSample" method="post" action="#" onSubmit="return ValidatePhoneNumber()">
    			<p>Enter a phone number : 
    				<input type="text" name="txtPhone">
    			</p>
    			<p> 
    				<input type="submit" name="Submit" value="Submit">
    			</p>
    		</form>
    	</body>
    	</body>
    </html>


    I need further help.

    Right now I am using hardcore values for comparing all 0's.

    Can anyone provide me a regular expression for comparing only 0's in a phone number.

    Thanks

  8. #8
    Unobtrusively zen silver trophybronze trophy
    SitePoint Award Recipient paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,233
    Mentioned
    42 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by dchopda View Post
    Can anyone provide me a regular expression for comparing only 0's in a phone number.
    Yes.

    Sometimes it's better to look for the opposite of what you're after, and then invert it.

    In this case, invert a positive match for all zeros.

    Code javascript:
    if (!text.match(/^0+$/)) {
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  9. #9
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    15,862
    Mentioned
    8 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by pmw57 View Post
    Code javascript:
    if (!text.match(/^0+$/)) {
    That doesn't take into account that 000 is a valid phone number.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •