Sunday, 17 July 2016

ASP.Net TextBox validation using JavaScript

In this article, we are going to validate ASP.Net TextBox control using JavaScript.

Related Article

  1. ASP.Net CustomValidator control to check valid E-Mail
  2. Simple registration form with client side validation in
  3. Call JavaScript function from code behind C# file in ASP.Net
  4. Simple registration form with server side validation in
  5. Show ValidationSummary ErrorMessage in popup in

In Designer File

In designer file, create two TextBox controls which will take First Name and Last Name as a input strings. And create a button control which will validate the text-boxes. If validation is successful then the form will be posted to server. Below is the designer file look like.

ASP.Net TextBox validation using JavaScript designer

Below is the designer code.

<table style="border: 1px solid black;">
        <td>Enter First Name</td>
            <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>
        <td>Enter Last Name</td>
            <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return ValidateForm()"

Button control has used two click events OnClientClick and OnClick. On OnClientClick, we are calling JavaScript method ValidateForm(). When ValidateForm() returns true then btnSubmit_Click method will get called. Below is the JavaScript code. Include the JavaScript in the head section of your page.

<head id="Head1" runat="server">
<script type="text/javascript" language="javascript">
    function ValidateForm() {
        var txtFirstName = document.getElementById("txtFirstName").value;
        var txtLastName = document.getElementById("txtLastName").value;

        if (txtFirstName.trim() == "") {
            alert("Enter first name");
            return false;
        if (txtLastName.trim() == "") {
            alert("Enter last name");
            return false;


Output will be shown as below.

ASP.Net TextBox validation error in alert


Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive