Tuesday, March 22, 2011

Validate Phone Number

In this blog, I am going to explain about validating phone number text box in ASP.NET using Java Script.
Create a Text Box control, given below.
<asp:TextBox ID="txtPhoneNumber" runat="server" Height="18px" Width="129px"
                        onchange = "this.value = ValidatePhone(this);"></asp:TextBox>

onchange() is used to call a JavaScript function, named as ValidatePhone(). Pass the TextBox control as an argument.

I use Regular Expression to validate phone number. Java Script function could be
function ValidatePhone(phonenumber) {
    var regex = /^\(?([2-9][0-8][0-9])\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$/;

    if (regex.test(phonenumber.value)) {
        var newPhoneNumber = phonenumber.value.replace(regex, "($1) $2-$3");
        return newPhoneNumber;
    } else {
       
        alert(" Invalid phone number");
        return phonenumber.value;
        }
}

The basic Rules of Valid phone numbers according to the North American Numbering Plan are,
  • Area codes start with a number from 2–9, followed by 0–8, and then any third digit.
  • The second group of three digits, known as the central office or exchange code, starts with a number from 2–9, followed by any two digits.
  • The final four digits, known as the station code, have no restrictions.
These rules can easily be implemented with a few character classes:
^\(?([2-9][0-8][0-9])\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$
Generally, the phone number format includes 4125671234, 412-567-1234, 412.567.1234, 412 567 1234, (412) 567 1234, and all related combinations. If the phone number is valid, you can convert it to your standard format, (412) 567-1234 for maintaining consistency. This can be done by using replace() method. The replacement is ($1) $2-$3. Now the phone number will be changed into (412) 567-1234.
Happy Coding!!!

Monday, March 21, 2011

How To

Change the first letter of the Text Box into Upper Case

How to change the first letter of the Text Box into Upper Case
            In this blog, I am going to explain how to change the first letter of the text box control into uppercase. For this, you need to write a JavaScript code.
First create an asp.net text box control in the page, as given below.
<asp:TextBox ID="FirstName" onchange = "convert(this);" runat="server"></asp:TextBox>

The method name convert() is used to call a JavaScript function. Define the method as given below.
<script type="text/javascript" language="JavaScript">
function convert(controlname)
{
 
    return;
}
</script>

When the text box lost its focus will change the first letter of the word into upper case.