Search code examples
asp.net-mvcunobtrusive-javascriptunobtrusive-validation

MVC 3 Cant turn off unobtrusive javascript


I've been implementing the new unobtrusive javascript in my mvc 3 project (using RC1). I've added the 3 required scripts to a "master" layout page. All is working well.

However I have a view where I want to use some normal jquery validation to validate a textbox. To be exact I want to check an entry exists, and that it is numeric.

So on the page my js looks like so...

<script language="javascript" type="text/javascript">
$(document).ready(function(){
    $('#SomeForm').validate({
        errorClass: "field-validation-error",
        validClass: "field-validation-none",
        errorElement: "label",
        rules: {
            ItemCount: {
                required: true,
                number: true
            }
        },
        messages: {
            ItemCount: {
                required: "Please specify the number of items available",
                number: "Please specify a valid number"
            }
        }
    });
});

However this was not working. So on my master layout page I commented out the reference to the jquery.validate.unobtrusive.min.js file and hey presto it worked.

So I thought, must be something to do with the unobtrusive bits and pieces, so if I turn it off (which I'd read that you can) all will be well.

So, in the view page I added the following line

Html.EnableUnobtrusiveJavaScript(false);

But no joy. The only way I can get it to work is to remove the reference to the unobtrusive js file.

Surely this can't be the case. I must be being stoppid right?

Thanks D


Solution

  • jquery.validate.unobtrusive.min.js already registers a validate function on the form which is conflicting with your own. So instead of calling the validate function you may try adding rules.

    $("#myinput").rules("add", {
        required: true,
        minlength: 2,
        messages: {
            required: "Required input",
            minlength: jQuery.format("Please, at least {0} characters are necessary")
        }
    });