Click here to Skip to main content
15,885,910 members
Articles / Web Development / ASP.NET
Tip/Trick

Client Side Validation using JavaScript

Rate me:
Please Sign up or sign in to vote.
4.67/5 (16 votes)
15 Jun 2012CPOL1 min read 279K   20   9
In this article we will see how we can validate a TextBox and DropDownList using JavaScript.

Introduction

In this article how we can validate TextBox and DropDownList using JavaScript.

Image 1

Using the code

In this article we will see how we can validate a TextBox and DropDownList using JavaScript.

Firstly we add some textboxes and a dropdownlist to an .aspx page, as follows:

XML
<table class="style1">
    <tr>
        <td>
            <asp:Label ID="Label1" runat="server" Text="First Name"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="Label2" runat="server" Text="Last Name"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td class="style2">
            <asp:Label ID="Label3" runat="server" Text="Email"></asp:Label>
        </td>
        <td class="style2">
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="Label4" runat="server" Text="Pin"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtPin" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
       <td>
            <asp:Label ID="Label5" runat="server" Text="URL"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtURL" runat="server"></asp:TextBox>
        </td>
    </tr>
     <tr>
       <td>
            <asp:Label ID="Label6" runat="server" Text="City"></asp:Label>
       </td>
       <td>
           <asp:DropDownList ID="DropDownList1" runat="server" Height="20px" Width="135px">
              <asp:ListItem></asp:ListItem>
              <asp:ListItem>Select</asp:ListItem>
              <asp:ListItem>Chandigarh</asp:ListItem>
              <asp:ListItem>Delhi</asp:ListItem>
              <asp:ListItem>Mumbai</asp:ListItem>
           </asp:DropDownList>
       </td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td>
            <asp:Button ID="Button1" runat="server" Text="Submit" 
                OnClientClick="return validate();" onclick="Button1_Click" />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
</table>

OnClientClick="return validate();" is used to call the JavaScript function on click of the Submit button.

Now we will add JavaScript code to implement client side implementation.

Firstly we will add a JavaScript function:

JavaScript
 <script type="text/javascript">
    function validate() 
    {
	//code here....
}
</script>

Now in the validate() function, we will get the value of textboxes and the dropdownlist like below:

JavaScript
var Firstname = document.getElementById('<%=txtFirstName.ClientID %>').value;
var LastName = document.getElementById('<%=txtLastName.ClientID %>').value;
var Email = document.getElementById('<%=txtEmail.ClientID %>').value;
var Pin = document.getElementById('<%=txtPin.ClientID %>').value;
var WebUrl = document.getElementById('<%=txtURL.ClientID %>').value;
var City = document.getElementById('<%=DropDownList1.ClientID %>').value;

Now we check textboxes are blank or not like below:

JavaScript
if (Firstname == "") 
{
    alert("Enter First Name");
    return false;
}

if (LastName == "") {
    alert("Enter Last Name");
    return false;
}

if (Email == "") {
    alert("Enter Email");
    return false;
}

 if (Pin == "") {
    alert("Enter Pin");
    return false;
}
 if(WebUrl == "")
{
   alert("Enter Web URL");
   return false;
}
if (City == "")
{
   alert("Select City");
   return false;
}

Now for email value we will create a parameter that finds if the email format is valid or not.

JavaScript
var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
            var EmailmatchArray = Email.match(emailPat);

Here we check it is valid or not..

JavaScript
if (EmailmatchArray == null) {
    alert("Your email address seems incorrect. Please try again.");
    return false;
}

Now for Pin No. value, we will create a parameter that finds if the PinNo format is valid or not.

JavaScript
var digits = "0123456789";
var temp;

for (var i = 0; i < document.getElementById("<%=txtPin.ClientID %>").value.length; i++) {
    temp = document.getElementById("<%=txtPin.ClientID%>").value.substring(i, i + 1);
    if (digits.indexOf(temp) == -1) {
        alert("Please enter correct pin code");
        document.getElementById("<%=txtPin.ClientID%>").focus();
        return false;
    }
}

Now for the WebUrl value, we will create a parameter that finds if the WebUrl format is valid or not.

JavaScript
var Url = "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$";
var matchURL = WebUrl.match(Url);
if (matchURL == null) {
   alert("Web URL does not look valid");
   document.getElementById("<%=txtURL.ClientID %>").focus();
   return false;
}

We have already checked if the dropdownlist value is blank or not. If we want that dropdownlist value should not be selected, then we will add one more checkpoint as follows:

JavaScript
if (City == "Select") {
   alert("Select City");
   return false;
}

Following is the complete JavaScript function:

JavaScript
<script type="text/javascript">
function validate() 
{
    var Firstname = document.getElementById('<%=txtFirstName.ClientID %>').value;
    var LastName = document.getElementById('<%=txtLastName.ClientID %>').value;
    var Email = document.getElementById('<%=txtEmail.ClientID %>').value;
    var Pin = document.getElementById('<%=txtPin.ClientID %>').value;
    var WebUrl = document.getElementById('<%=txtURL.ClientID %>').value;
    var City = document.getElementById('<%=DropDownList1.ClientID %>').value;

    if (Firstname == "") 
    {
        alert("Enter First Name");
        return false;
    }
    if (LastName == "") {
        alert("Enter Last Name");
        return false;
    }
    
    if (Email == "") {
        alert("Enter Email");
        return false;
    }
    var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
    var EmailmatchArray = Email.match(emailPat);
    if (EmailmatchArray == null) {
        alert("Your email address seems incorrect. Please try again.");
        return false;
    }

    
    if (Pin == "") {
        alert("Enter Pin");
        return false;
    }
    var digits = "0123456789";
    var temp;

    for (var i = 0; i < document.getElementById("<%=txtPin.ClientID %>

When user enters wrong information or may the user leaves a textbox blank, then the client side validation will be work. This will reduce server traffic. I hope this helps you.

License

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


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionJavaScript form Validation in asp.net Pin
santosh068331-Oct-18 20:17
santosh068331-Oct-18 20:17 
QuestionClient Side Validation using JavaScript Clariffication Pin
thiyajan13-Nov-15 17:08
thiyajan13-Nov-15 17:08 
GeneralMy vote of 5 Pin
joelprabhu17-May-15 21:09
joelprabhu17-May-15 21:09 
Questionkarthick Pin
Karthick2it19-Aug-14 23:50
Karthick2it19-Aug-14 23:50 
Questionrelated to last reply Pin
Er Bhargav Dudani10-Jul-13 23:23
professionalEr Bhargav Dudani10-Jul-13 23:23 
QuestionI have doubt in the email wild card format Pin
nachia31-Mar-13 6:53
nachia31-Mar-13 6:53 
QuestionHi Navjot, Pin
kajal856-Oct-12 0:00
kajal856-Oct-12 0:00 
AnswerRe: Hi Navjot, Pin
sandeepkumardhn8-May-14 23:49
sandeepkumardhn8-May-14 23:49 
QuestionNot finished Pin
EuphorialXTC15-Jul-12 22:29
EuphorialXTC15-Jul-12 22:29 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.