.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Javascript >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Validate Phone number from Javascript

Posted By:Mohan Raut       Posted Date: September 08, 2008    Points: 10    Category: Javascript    URL: http://www.dotnetspark.com  
 

Sometimes we need to validate phone number in client side using scripting language.Below is the sample code to validate phone number using javscript

in aspx page



here is the textbox for Phone, below is the javascript funtion to validate the textbox..
//************************************
 function trimString (str){
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function CheckPhone(source, args)
  {
    var ControlId = source.id;
    var ControlId = ControlId.replace("CusValid","");
    //alert(ControlId);
    var TextObj = document.getElementById(ControlId);
    //var iPhone = document.getElementById("<%= txtPhone1.ClientID %>");
    var flag = check_phonenumber(TextObj);
   
      if (flag==true)
      {   
       args.IsValid = true;       
      }else
      {
      args.IsValid = false;     
      }
  }
 
  function check_phonenumber(phoneBox){
    var phoneVal = trimString(phoneBox.value.toString());
    phoneBox.value=trimString(phoneBox.value.toString());
   
    var valid;
    valid=true;
    var mstr=phoneVal.toString();
    var count=0;
    for (var i = 0;i < mstr.length;i++){
        var oc = mstr.charAt(i);
        if ((oc < "0" ||oc > "9")){
            count++;
        }
    }
   
    if(mstr.length>0){
        var oc = mstr.charAt(0);
        if ((oc < "0" ||oc > "9")&& oc!="+"){
            valid=false;
        }
    }
    for (var i = 1;i < mstr.length;i++){
        var oc = mstr.charAt(i);
        if ((oc < "0" ||oc > "9")&& oc!=" "&& oc!=","&& oc!="-"&& oc!="+" && oc!="(" && oc!=")"){
            valid=false;
        }
    }
    if (valid == false){       
        return(false);
    }
    return(true);
}
//*****************************************
best thing is that u can customise this function as per our phone format if u understood the code...


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply

    Read also another Resources from the same Author

Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend