Powered by Blogger.

Thursday, February 27, 2014

Simple JavaScript textbox validation example in Asp.Net

In this post we will discuss about a simple textbox required field validation in Asp.Net using JavaScript.

Also you can check my previous articles on:

- Sql Server 2008 joins tutorial

- How to download file in C#.Net?

- RequiredFieldValidator example in Asp.Net

Here in this exapmle when ever a user clicks on the submit button without entering anything in the textbox, one alert message will be shown as "Enter Name".

We have written the JavaScript function and calling that function in the OnClientClick property of the button.

Below is the full code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JavaScriptValidation.aspx.cs"
    Inherits="JavaScriptValidation" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Simple JavaScript validation example</title>
    <script language="javascript" type="text/javascript">
        function validateName() {
            if (document.getElementById("txtName").value == "") {
                alert('Enter Name');
                return false;
    <form id="form1" runat="server">
        Enter Name:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="btnTest" runat="server" Text="Click to Validate" OnClick="btnTest_Click"
            OnClientClick="return validateName();" />

The output will be like as shown in the figure below: