[英]How to make a field required, based on the value of another field
I have a ViewModel with some public properties that have data annotations, like this: 我有一个ViewModel,带有一些带有数据批注的公共属性,如下所示:
[Required]
public string PointOfContact { get; set; }
Which works just fine. 哪个工作正常。 I've got all of the necessary plumbing in place to display the proper control formatting and error messages when validation fails. 我已准备好所有必要的管道,以在验证失败时显示正确的控件格式和错误消息。
However, I have some fields that are conditionally required based on the value of a checkbox. 但是,我有一些字段是基于复选框的值有条件要求的。 For example: 例如:
public bool Briefing { get; set; }
public DateTime BriefingTime { get; set; }
In this case, I only want BriefingTime to be required if the checkbox that is bound to the Briefing property is checked. 在这种情况下,如果选中了绑定到Briefing属性的复选框,我只希望BriefingTime是必需的。 The visibility of BriefingTime is already bound to Briefing, so all I need is for it to have the usual Required behavior when the checkbox is checked. BriefingTime的可见性已经绑定到Briefing,因此我所需要的是在选中复选框时使其具有通常的Required行为。
Is there a way to do this out-of-the-box, or do I need to write my own Data Annotation class? 有没有一种现成的方法,还是我需要编写自己的数据注释类? What would such a class look like? 这样的课程是什么样的?
You could write your own custom ValidationAttribute
: 您可以编写自己的自定义ValidationAttribute
:
public class BriefingTimeRequiredAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var model = (MyModel)validationContext.ObjectInstance;
if (model.Briefing && !model.BriefingTime.HasValue)
{
return new ValidationResult("BriefingTime is required.");
}
return ValidationResult.Success;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.