Friday, 29 May 2015

How to use Javascript Validation in Asp.net


Today I am going to show you how we can use Javascript validation in Asp.net.

We will have TextBox and Dropdown in the following example.



Home.aspx

<table class="style1">
    <tr>
        <td>
            <asp:Label ID="lblname" runat="server" Text="Name"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="lbladdress" runat="server" Text="Address"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td class="style2">
            <asp:Label ID="lblemail" 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="lblcountry" runat="server" Text="Country"></asp:Label>
       </td>
       <td>
           <asp:DropDownList ID="ddlcountry" runat="server" Height="20px" Width="135px">
              <asp:ListItem></asp:ListItem>
              <asp:ListItem>Select</asp:ListItem>
              <asp:ListItem>India</asp:ListItem>
              <asp:ListItem>China</asp:ListItem>
              <asp:ListItem>Pakistan</asp:ListItem>
           </asp:DropDownList>
       </td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td>
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
                OnClientClick="return validate();" onclick="btnSubmit_Click" />
        </td>
    </tr>
   
</table>


Javascript

<script type="text/javascript">
function validate() 
{
    var name = document.getElementById('<%=txtname.ClientID %>').value;
    var address= document.getElementById('<%=txtaddress.ClientID %>').value;
    var email = document.getElementById('<%=txtemail.ClientID %>').value;
    var country = document.getElementById('<%=ddlcountry.ClientID %>').value;

    if (name == "") 
    {
        alert("Enter Name");
        return false;
    }
    if (address == "") {
        alert("Enter Address");
        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 (country == "Select") {
   alert("Select Country");
   return false;
  }
</script>

No comments:

Post a Comment

Join US Our Community
×