Validating data using ASP.NET Custom Validation control and jQuery AJAX

It's a common situation when a user is filling out a long form and when he eventually submit the form, your website come back and say that some value has already been taken and now user will have to choose another value instead. Wouldn't it be nice if user find out that the value he has just entered is invalid or username he has entered has already been taken?

An example of this is while registering for Gmail or Yahoo mail when you choose email that you want to create and there is a button that quickly check the availability to tells you whether its available or not without full page refresh. Today we are going to implement similar functionality using jQuery AJAX, ASP.NET web services and ASP.NET custom validation control.

So in order to get started create a new website and add following files:

  1. Web form: Default.aspx (if you don't have already)
  2. Web service: UserNameWebService.asmx (or some different name, totally depends on you)
  3. Reference to jQuery library either by downloading from jQuery website or from Microsoft CDN website (In this case we are going to use Microsoft CDN)

Once you have all this ready, lets add some code to our web service: (For Demo purpose we are going to evaluate our condition with static data but in real world this data will come either from database or from Membership (in case if you are checking that username is already taken or not))

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]

public class UserNameWebService : System.Web.Services.WebService {

[WebMethod]

public bool Username(string usern)

{

bool isValidated=false;

if (usern.Equals("DevTechie"))

{

isValidated = true;

}

return isValidated;

}

}

 

Since we are going to use JavaScript to call our web service, let's add [System.Web.Script.Services.ScriptService] attribute to the class (as shown above).

In this code above, we are creating a simple method that accept string value (in this case username) and return Boolean after comparing it with static string (in this case DevTechie)

Now we need to add jQuery script library reference to head section of Default.aspx:

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js "></script>

 

After this we will add a textbox and a custom validation control to the page and set its properties as follows:

 

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:CustomValidator ID="CustomValidator1" runat="server"

ErrorMessage="Text has already been taken" ControlToValidate="TextBox1" ForeColor="Red"

ClientValidationFunction="TextValidation"></asp:CustomValidator>

 

In this case, we are just focusing on client side validation but it's recommended to use client side as well as server side validation (just as a fallback so if JavaScript is disabled on user's browser, page validation would still work)

Now it's time to define our JavaScript function for client side validation with name mentioned above "TextValidation"

<script type="text/javascript">

function TextValidation(src, args) {

var valid;

$.ajax({

url: "UserNameWebService.asmx/Username",

data: "{'usern' : '" + args.Value + "'}",

type:'POST',

contentType: "application/json",

dataType: "json",

async:false,

success: function (data) {

valid = data.d;

}

 

});

 

args.IsValid = !valid;

}

 

</script>

 

What we are doing here is: we are using standard asp.net function signature which accept source of call and arguments as parameter, and in argument we get value that was entered in associated control that needs validation as well as a property that we will have to set based on our logic from web service named IsValid.

Using jQuery Ajax we are passing

  1. "URL" of our web service with its method name at the end
  2. "data" which is basically parameter(s) that our web method take
  3. "type" of request which in this case is post, then type of content (this is important to set because by default web service return XML formatted response), 4)
  4. "dataType" which define what kind of data we need to parse
  5. "async" property is important because that tells our page that wait for response from service
  6. finally our "success" callback method, which define what we need to do when web service return the result

In this case, we are setting args.IsValid to opposite of what we are getting from web service so if true then false or if false then true.

This is it; now let's browse the page and type "DevTechie":

 

 

You will get a validation error message that text has been taken and if we change the value to something else the error will disappear.

 

Tags: , ,

AJAX | ASP.NET | jQuery