对多个字段进行不显眼的客户端验证

Unobtrusive client-side validation on multiple fields

我想根据多个字段的值验证模型。我的模型如下所示:

public class CreateStudentEventViewModel : IValidatableObject
{
    [Required]
    public DateTime StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public DateTime? StartTime { get; set; }
    public DateTime? EndTime { get; set; }

    public bool HasTimes { get; set; }
    public bool IsMilestone { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();

        // some other random test
        if (this.IsMilestone)
        {
            if (this.EndDate != null)
                results.Add(new ValidationResult("Event is a milestone but has an end date selected."));
        }

        if (this.HasTimes)
        {
            if (this.StartTime == null)
                results.Add(new ValidationResult("Event has times, but no start time was selected."));

            if (this.EndTime == null)
                results.Add(new ValidationResult("Event has times, but no end time was selected."));
        }

        return results;
    }
}

所以在服务器端,Validate() 方法中的代码将是 运行。但是我怎样才能以某种方式将其转换为客户端呢?我是否必须以某种方式将其重写为 jQuery 验证的自定义规则?

foolproof 有许多有用的验证属性,它们应该满足您指定的条件,特别是 [RequiredIfTrue] 属性。这些将根据另一个 属性.

的值为您提供客户端和服务器端验证
public class CreateStudentEventViewModel
{
  [Required]
  public DateTime StartDate { get; set; }
  [RequiredIfTrue("IsMilestone")]
  public DateTime? EndDate { get; set; }
  [RequiredIfTrue("HasTimes")]
  public DateTime? StartTime { get; set; }
  [RequiredIfTrue("HasTimes")]
  public DateTime? EndTime { get; set; }
  public bool HasTimes { get; set; }
  public bool IsMilestone { get; set; }
}

如果您想创建自己的属性来提供客户端验证,则需要继承 ValidationAttribute 并实现 IClientValidatable。这篇文章虽然有点老了,但是THE COMPLETE GUIDE TO VALIDATION IN ASP.NET MVC 3还是个不错的参考。