views:

270

answers:

2

hi guys,

i am tasked with the job of creating client-side validation on a form in an asp.net MVC 2 application, which has a modal window (the modal exists as part of the wrapping form, it is not a form unto itself). how would i go about providing validation for these text field inputs while the modal is visible, but do not validate while the modal is not displayed (as to not cause problems in the rest of the form if the modal window is never required)

What is the best approach to achieve this functionality?

thanks, Nick

A: 

If you're using the jQuery validation plugin (unclear from your tags), just give it a dependency expression that includes :visible on required, like this:

$("form").validate({
  rules: {
    formFieldName: { required: "#formFieldID:visible" }
  }
});
Nick Craver
yes i'm using the jquery.validate plugin, the validation code is autogenerated by MVC, so would this still work? alternatively is there a way to get MVC to generate such logic itself (custom validator perhaps?)
mr.nicksta
@nick - I don't think you can, since the annotations on the model shouldn't know anything about the view and what's visible, you can add the rule in after the generated ones with this though: `$("#formFieldID").rules("add", { required: "#formFieldID:visible" });`
Nick Craver
A: 

Flag the fields for validation when you load the form. When the window displays flag the forms for validation when it is hidden deflag them.

Or have an array of the fields to be validated and add the fields from the window to this when it is displayed and remove them when it is not.

matpol