Saturday, January 15, 2011

MVC3 validates hidden fields using jquery validation

I am not sure about you, but I rarely, if ever, want to validate a form field that is hidden from view!

Consider the case where you have a several required fields on the screen and the user can take some action that causes some fields to then be hidden.  Well, using the default unobtrusive jquery validation, it will still validate those fields.   If you do not have a 'SummaryValidation', this means the form just will not submit - no errors or anything because the error is displayed on a hidden field!

How do we get it to stop doing this?   For now, I know of only one way.  You need to add one line of code into the jquery.validate.unobtrusive.js file.

Add line 97 as shown below (and of course the comma at the end of line 96):

15 comments:

Matt S. said...

Nice! Did you submit this to Connect?

Wayne Brantley said...

No, I did not...I guess I should...

Matt S. said...

This is definitely an oops on their part. I cannot imagine it's by design.

Rafa said...

Thats a good solution, but...

how do u update the modelstate in the controller after u set the hidden value ???

Wayne Brantley said...

This only stops the validation on the client side. The server side will still validate and modelstate will still show it.

Rafa said...

I know... but imagine that my hidden field is the DateCreated.

in the Controller i will set the DateCreated. And the model now should be valid... how to do it ??

Wayne Brantley said...

@Rafa - I am not sure what you are asking exactly.

Rafa said...
This comment has been removed by the author.
Anonymous said...

Look into http://stackoverflow.com/questions/2623514/jquery-validate-ignore-elements-with-style. Seems to solve this issue.

Wayne Brantley said...

yes, you can do it with jquery like is show at stack overflow, but making the above change will make it happen automatically with the unobtrusive validation.

Ed said...

Changing the jQuery code would invalidate your ability to include that file through a public CDN though.

MJ said...

I can not get this to work, does your input have style="visibility:hidden", will this work with Jquery.hide()?

Anonymous said...

Awesome. Works like a charm.

Unknown said...

Sorry. But it doesn't work for me. I'm using this code to disable validation:
$('#Form').validate({
onsubmit: false,
onkeyup: false,
onfocusout: false,
onclick: false
});

Anonymous said...

I know this post is old, but Im having same issue and the image above is broken - please can you just post the line of code.
Thanks
Ian