Question

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

Was it helpful?

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")
    }
});

OTHER TIPS

I think the new Unobtrusive jQUery Adapter is designed in a way that you either enable it for the whole or none, you cannot conditionally enable/disable it for a specific view.

What version of MVC3 are you on is it CTP, Beta or RC? It works fine for me in RC using Razor. Please post the code from the view.

Try going to web.config and finding this:

  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

And set UnobtrusiveJavaScriptEnabled to false. There may be more keys with it though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top