I have a very simple contact form with fields like this:
<label>
First Name<em>*</em>
@Html.TextBox("txtFirstName", null, new { tabindex = "1"})
</label>
I want this field to be required so I’ve add some code to document ready:
$(function(){
$("#contactForm").validate({
rules: {
txtFirstName: { required: true}
/* also tried this */
txtFirstName: "required"
}
});
});
However, at this point it won’t require the field. What seems crazy is that if I add a “required” class attribute like so:
@Html.TextBox("txtFirstName", null, new { tabindex = "1", @class="required"})
It will validate, but I need more complex rules than just required. I need to check that certain options are chosen in a select list then certain fields should or should not be required.
I suspect that you have included the
jquery.validate.unobtrusive.jsscript to your page. This script registers its own.validatehandler on the form which obviously conflicts with yours. Thejquery.validate.unobtrusive.jsscript is used when you have a view model decorated with data annotations to perform validation and those data annotations are translated into HTML5 data-* attributes on the generated input fields. Those HTML5 data-* attributes are then interpreted by thejquery.validate.unobtrusive.jsscript which registers a.validatehandler on the form.If you want to define your own validation rules and register a custom
.validaterules you will have to do it manually (as you did) and remove any traces of the built-in unobtrusive validation script from this page.The reason why validation works when you add the
class="required"attribute on the input field is because thejquery.validate.unobtrusive.jspicks it up and it includes it in its own rules when it configures the plugin by registering a.validatemethod on the form.