jQuery.validate is ignoring my rule declarations

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.

Answers


I suspect that you have included the jquery.validate.unobtrusive.js script to your page. This script registers its own .validate handler on the form which obviously conflicts with yours. The jquery.validate.unobtrusive.js script 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 the jquery.validate.unobtrusive.js script which registers a .validate handler on the form.

If you want to define your own validation rules and register a custom .validate rules 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 the jquery.validate.unobtrusive.js picks it up and it includes it in its own rules when it configures the plugin by registering a .validate method on the form.


Need Your Help

Instance variable in Java Spring Bean

java multithreading spring thread-safety heap

I'm developing a Java Spring MVC project and i hesitate using instance variable in Java Spring Bean.I want to ask some question about this subject.

Rails: Referring back to model the object belongs to

ruby-on-rails model include relationship

This is probably a dumb question, but I can't seem to find a good answer. I want to know the best way to refer back to the model that an object belongs to.