Click here to Skip to main content
Click here to Skip to main content

Validate Phone or Fax Number using JavaScript

By , 7 May 2013
 

Introduction

This is a small JavaScript function that is useful for validating a phone/fax number. It gives an alert message if user enters data other than numbers.

Using the Code

We will create one JavaScript function called "ValidateNo".

In this function, there are two arguments:

  1. NumStr: This is the value which you want to validate. It will come from your form control. It may by TextBox control (HTML or ServerControl).
  2. String: This is a predefined format which you can use to validate phone/fax number. It may contain +, - and space. You can modify it as per your requirement.

Below is the JavaScript function ValidateNo, which we create for validation purpose.

function ValidateNo(NumStr, String)
{
    for(var Idx=0; Idx<NumStr.length; Idx++)
    {
        var Char = NumStr.charAt(Idx);
        var Match = false;

        for(var Idx1=0; Idx1<String.length; Idx1++)
        {
            if(Char == String.charAt (Idx1))
                Match = true;
        }

        if (!Match)
            return false;
    }
    return true;
}

We can put ValidateNo function in common JavaScript file, from where we can access it in all pages of the application.

Now we create one JavaScript function called "ValidateDetail".

function ValidateDetail()
{
    if(document.getElementById("phone").value == "")
    {
       alert("Please specify Phone number");
       document.getElementById("phone").focus();
       return false;
    }

    if(!ValidateNo(document.getElementById("phone").value,"1234567890"))
    {
        alert("Please enter only Number");
        document.getElementById("phone").focus();
        return false;
    }

    return true;
} 

Now you can call this JavaScript "ValidateDetail" function for validating your phone and fax number.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Pradip P Patel
Team Leader
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
General[My vote of 1] this is awful...memberSeishin#9 May '13 - 4:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130513.1 | Last Updated 7 May 2013
Article Copyright 2013 by Pradip P Patel
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid