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

时间:2015-03-26 00:46:16

标签: jquery asp.net-mvc unobtrusive-validation

我想根据多个字段的值验证模型。我的模型看起来像这样:

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验证的自定义规则?

1 个答案:

答案 0 :(得分:1)

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是一个很好的参考。