0
votes

I'm trying to do some conditional validation using the jQuery validator.

I have a wizard in javascript that calls the validate method when moving to the next step:

var validator = $("form").validate();
var anyError = false;

step.find("input").each(function () {
    if (!validator.element(this)) {
        // validate every input
        anyError = true;
    }
});

if (anyError) {
    return false;
}

All works fine when I have a [Required] attribute on the model.

However I have this scenario:

  • I have a drop down with a choice: Email or Ftp
  • When the Email option is selected I want to show the email address field and add validation
  • When the Ftp option is selected I don't want to validate the email address

Here's the html snippet for the email address.

<div class="email-address" style="display: none;">
   <label class="fullwidth" for="EmailAddress">Email Address</label>
   @Html.TextBoxFor(m => m.EmailAddress, new { @class = "longtext" })
   <div id="email-validation">
   </div>

I've tried all sorts but the next button validation routine always thinks the form is valid. For example.

$("form").validate({
    errorLabelContainer: '#email-validation',
    rules: {
        EmailAddress: {
           required: true
        }
    },
    messages: {
        EmailAddress: "Please enter an email address"
    }
});

Any help appreciated.

2
check this article: blogs.msdn.com/b/simonince/archive/2011/09/29/… I had the same problem, a dropdown to validate a field, and this article is really useful. - Gradile

2 Answers

0
votes

I'm not certain, but i'm pretty sure you can't use standard jquery-validation in conjunction with MVC3 client-side validation.. You have to do one or the other.

To be more specific, MCV3 client-side validation adapts jquery-validation for it's own use, and this conflicts with using jquery-validation stand-alone.

0
votes

I would use the fact that disabled inputs do not participate in validation. Add required for server side but just disable and hide EmailAddress when ftp is selected.