1

I have a ViewModel with properties for a TextBox and a Checkbox:

public bool SendAlerts { get; set; }
public string EmailAddress { get; set; }

I need to validate the EmailAddress field (textbox) to ensure there is an email address ONLY if the checkbox in my view (which binds to the SendAlerts property) is checked. If the checkbox is not checked, then it doesn't matter if the EmailAddress textbox is empty.

How do I go about implementing this conditional validation? I am using DataAnnotations against some of the other properties in my ViewModel, like a straight forward 'Required' annotation (but I can't use that for this scenario as it's conditional).

I have used CustomValidation for a couple other properties in my view model i.e.

public static ValidationResult IsTitleValid(object value)
{ ... }

However, I only have 1 object value with this approach, rather than being able to reference both checkbox AND textbox values.

What's the best way to approach this using MVC?

Jalal Said
  • 15,906
  • 7
  • 45
  • 68
marcusstarnes
  • 6,393
  • 14
  • 65
  • 112

1 Answers1

4

We were recently forced to do similar things at work, and could not find a better solution than the following: http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx

Updated to MVC3 here: http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx

Basically you introduce a new attribute, RequiredIf. With this solution you get client-side validation as well.

nillls
  • 625
  • 4
  • 11
  • Thanks, this works great. If I wanted an additional step of validation on the back if this so not just performing the conditional 'required' validation check, but if it IS required, then check if the provided value is a valid email address (I have a function already to validate email addresses) - any idea how best to implement that with this approach? – marcusstarnes Aug 08 '11 at 11:25