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 f
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
or false
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:
<asp:CustomValidator ID="CustomValidator1" runat="server" Display="None"
ClientValidationFunction="checkTextareaLengths">
</asp:CustomValidator>
JavaScript:
function checkTextareaLengths(source, args){
args.IsValid = true;
$('textarea').each(function(){
if($(this).text().lenght > 400)
args.IsValid = false;
});
}
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 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:
function validate_step(step_element) {
// find all validators on step_element and force validation
var validators = $(step_element).find("span[controltovalidate]");
var stepIsValid = true;
validators.each( function() {
ValidatorValidate(this); stepIsValid &= this.isvalid;
});
return stepIsValid;
}