Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

ASP.Net TextBox validation using JavaScript

In this article, we are going to validate ASP.Net Textbox control using Javascript.

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.

Below is the designer code.


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

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">
title>title>
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;
}
}
script>
head>

Output:

Output will be shown as below.



This post first appeared on ASPArticles, please read the originial post: here

Share the post

ASP.Net TextBox validation using JavaScript

×

Subscribe to Asparticles

Get updates delivered right to your inbox!

Thank you for your subscription

×