0

I am using jQuery Unobtrusive validation to validate fields on my forms.

I want fields in the form to be conditionally visible. For example, if the user selects a checkbox, several fields will appear.

I got all of this working, but if a user submits a form that includes hidden fields that are marked with the RequiredAttribute, then the form will not validate successfully because it thinks that the hidden fields are blank (note: I am talking about validation on the server-side - client-side validation is working as expected).

How can I exclude hidden fields from the server-side validation process?

p.s. I have already looked on Google and I did not find any elegant solutions for this - I feel like this should be something easy to do.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
William
  • 3,335
  • 9
  • 42
  • 74

1 Answers1

0

Here's a quick solution

Inherit your model class from IValidatableObject and override the Validate method. You can then write out your conditions and validate them in the override.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)       
{
    //Custom Validation
}

For Example lets say we have the following model

public class PersonModel : IValidatableObject
{


    public String Name { get; set; }

    public bool IsChecked { get; set; }


    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {

        //We only want to validate the name if the user has checked the checkbox(IsChecked)

        if(IsChecked && string.IsNullOrEmpty(Name))
        {
            yield return new ValidationResult("Name is required");
        }

        if(IsChecked && Name.Length > 20)
        {
            yield return new ValidationResult("Name cannot exceed more than 20 characters");
        }


    }

}

The only downside to using the IValidateObject method is it doesnt always play nice with dataannotations. For example, if the Validate method yielded at least one error then your dataannotations would not be validated. So I recommend removing your dataannotations if you were to use this method.

Hope this helps.

heymega
  • 9,215
  • 8
  • 42
  • 61
  • does this work with Unobtrusive Validation AJAX? (i.e. does it work with the built-in client validation)? – William Jul 30 '14 at 11:22