How can I best combine JQuery with ASP.NET client side validation model?
I've generally avoided implementing ASP.NET validation model because it always seems overkill for what I was doing. For the site I'm working on now I'm just collecting non critical user data and only need somewhat basic validation. I dont want messages appearing in the DOM or anything like that. I've always found it hard to get that to look right anyway.
But I need now to implement something a little more elegant. What I want to take advantage of in JQuery is clever search expressions like 'tell me if at least one of these checkboxes is checked'. I'm new to JQuery, but I think this is about 1 line of JQuery and a lot more complicated in the traditional ASP.NET model.
So I want to take full advantage of JQuery's abilities but not completely undemine ASP.NET's validation model.
My best approach so far is this (which pretty much goes behind the back of ASP.NET):
$('#<%=btnJoinMailingList.ClientID %>').bind('click', function(event) {
if (...) {
alert("You must enter a name");
return false;
}
return true;
});
What's a better approach here? Are there any recommended plugins for JQuery ?
PS. I don't want to use MVC model. I'm trying to create a very 'RAD' site and dont have time to delve into that fun new stuff yet.
ASP.NET webforms and jQuery's validation model is very, very similar, IMHO, in that both are client-side and implementing one of them does not necessarily undermine the other. The only real difference would be that, behind the scenes, ASP.NET validators will cause the
Page.Validate()
method to returns false if you have an unvalidated field.You may opt to hand-roll your own validation controls, and then cause the same behavior, but as you yourself have stated, that might be overkill.
jQuery also has its own Validator plugin which you might want to look at: http://docs.jquery.com/Plugins/Validation/Validator.
ASP.NET has many validation controls, one of them is the
CustomValidator
.You can give it a custom JavaScript function that uses jQuery and returns
true
orfalse
via argument. You can use this control to display the error message automatically, or just run the jQuery code and handle the display manually.Aspx:
JavaScript:
ASP.NET validator is a span with additional attributes. With jquery you can acces all validators on the page or filter they by any criteria supported by jquery. To force validation via javascript call ValidatorValidate function. For example: