I've put together a snippet of code in ASP.NET MVC in which I'm trying to use the addClassRules methods of jQuery's validator. From what I can tell I'm taking this straight of the examples on
http://docs.jquery.com/Plugins/Validation/Reference
But the page is just submitted it doesn't show any errors. I would like to use the "addClassRules" pattern for validation because I'm writing dynamic forms.
Here's my View.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ValidateMyForm</title>
<script src="<%= Url.Content("~/Scripts/jquery-1.4.1.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
</head>
<body>
<% using (Html.BeginForm()) { %>
<input type="text" value="" name="customer1" class="customer" />
<input type="text" value="" id="customer2" name="customer2" class="customer" />
<input type="text" name="customer3" class="customer" />
<p>
<input type="submit" name="submit" value="Submit" />
</p>
<% } %>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
// alias required to cRequired with new message
$.validator.addMethod("cRequired", $.validator.methods.required, "Customer name required");
// alias minlength, too
$.validator.addMethod("cMinlength", $.validator.methods.minlength, $.format("Customer name must have at least {0} characters"));
// combine them both, including the parameter for minlength
$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });
})
</script>
</body>
</html>
Any suggestions?
UPDATED: Fully functional code...
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ValidateMyForm</title>
<script src="<%= Url.Content("~/Scripts/jquery-1.4.1.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
</head>
<body>
<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "demoform" }))
{ %>
<%: Html.TextBox("myTextBox", "", new {@class = "cRequired"}) %>
<p>
<input type="submit" name="submit" value="Submit" />
</p>
<% } %>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
$.validator.addClassRules("cRequired", { required: true });
jQuery("#demoform").validate();
})
</script>
</body>
</html>