Validating textbox only if checkbox is checked usi

2019-07-22 19:27发布

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?

1条回答
太酷不给撩
2楼-- · 2019-07-22 20:13

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.

查看更多
登录 后发表回答