提交时验证数据注释模型中的多个字段(日期时间和布尔值)

Validating Multiple Fields (Datetime and Bool) in Data Annotation Model on Submit

目前我正在 MVC 3 环境中工作,我需要添加一个验证来验证 Dataannotation 模型中的 2 个字段,就像提交时触发的 [Required(ErrorMessage="Required!")] 验证一样。

目前,验证 [Required] 正在工作,但我需要检查 booldateTime 数据类型是否

这是我模型中的代码

public class NameInfo: IValidatableObject
    {

        [Display(Name = "Name")]
        [Required(ErrorMessage = "Required!")]
        public string Name{ get; set; }

        [Display(Name = "Start Date")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public Nullable<DateTime> StartDate { get; set; }

        [Display(Name = "Already Starting")]
        public bool IsStarting{ get; set; }


        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (!IsStarting&& !StartDate.HasValue)
            {
                yield return new ValidationResult("Required.", new[] { "StartDate" });

            }  
        }
    }

目前我正在使用 IValidatableObject 但它不会验证,除非 name 字段模型状态已经有效

提前致谢!

Currently im using IValidatableObject but its not validating unless the name Field modelstate is already Valid

DataAnnotationsIValidatableObject 不会一起验证。我的意思是 IValidatableObject 的验证方法只有在您的 DataAnnotations 有效时才会被调用。

要么编写您自己的 ValdiationAttribute,要么将所需的验证添加到您的 IValidatableObject

这是后者的一个例子...

public class NameInfo : IValidatableObject
{

    [Display(Name = "Name")]
    public string Name { get; set; }

    [Display(Name = "Start Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public Nullable<DateTime> StartDate { get; set; }

    [Display(Name = "Already Starting")]
    public bool IsStarting { get; set; }


    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {

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


        if (!IsStarting && !StartDate.HasValue)
        {
            yield return new ValidationResult("Required.", new[] { "StartDate" });

        }

    }
}