简体   繁体   English

如何根据另一个字段的值使字段为必填字段

[英]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.

相关问题 如果其他字段有价值,则填写必填字段 - Make a required field if the other field has value 如何基于Droplink字段中的原始值获取另一个字段值? - How to get another field value based on the raw value in a droplink field? 如果另一个输入字段为空,如何使用非侵入式验证将输入字段设为必填字段? - How to use unobtrusive validation to make an input field required field if another input field is empty? 如何正确地使byte []字段必填字段? - How to make byte[] field required field properly? 实体框架根据数据创建必填字段 - Entity Framework make a field required based on data 如何使下拉列表中的必填字段验证器? - How to make required field validator on dropdownlist? 如何根据剑道中另一列中的值禁用内联编辑中的字段? - How to disable field in inline editing based on value in another column in Kendo? 自定义属性验证:根据所选选项使字段为必填 - Custom Attribute Validation: make field required based on selected option 如何创建必填字段值对象 - How to create a Required Field Value Object 使用Ajax和C#根据另一个字段更改字段值 - Change field value based on another field with Ajax and c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM