ASP.NET Validation and jQuery

Posted on May 21, 2009 by Frederik Vig in ASP.NET, JavaScript

Recently I was working on a simple form that used the ASP.NET Validation controls for validation. This worked fine when doing a regular Postback to the server with the data. However I wanted to use Ajax to make it a little faster and the user experience better.

One of the problems I had was that when I hooked into my buttons click event with jQuery I needed to make sure the form validated before sending it to my web method. That’s when I came across this little piece of JavaScript.

if (Page_IsValid) {

Which does the same thing as Page.IsValid on the server

Below is some simple sample code.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <script src="" type="text/javascript"></script>
    <style type="text/css">
        fieldset em { color: Red; }
    <form id="form1" runat="server">
            <asp:Label runat="server" AssociatedControlID="txtName">Name: <em title="Required">*</em></asp:Label>
            <asp:TextBox runat="server" ID="txtName" ValidationGroup="Form" />
            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtName" Text="Name is missing" ValidationGroup="Form" />
            <asp:Button runat="server" ID="btnSend" Text="Submit" ValidationGroup="Form" OnClick="btnSend_Click" />
    <p id="result">
            <asp:Literal runat="server" ID="ltlResult" />
    <script type="text/javascript">
        $("#<%= btnSend.ClientID %>").click(function() {
            if (Page_IsValid) {
                var name = $("#<%= txtName.ClientID %>").val();
                    type: "POST",
                    url: "Default.aspx/YourName",
                    data: "{name:'" + name + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                return false;
using System;
using System.Web;
using System.Web.Services;
using System.Web.UI;
public partial class _Default : Page 
    protected void btnSend_Click(object sender, EventArgs e)
        if (Page.IsValid)
            ltlResult.Text = string.Format("Your name is: {0}", HttpUtility.HtmlEncode(txtName.Text));
    // Make sure to add the [WebMethod] attribute and make the method static
    public static string YourName(string name)
        return string.Format("Your name is: {0}", HttpUtility.HtmlEncode(name));

The reason I still have the btnSend_Click method is in case the user does not have JavaScript enabled.

Related Posts: