【问题标题】:Unobtrusive client-side validation on multiple fields对多个字段进行不显眼的客户端验证
【发布时间】:2015-03-26 00:46:15
【问题描述】:

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

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

【问题讨论】:

  • 您需要创建自己的属性,该属性继承自ValidationAttribute 并实现IClientValidatableThis article 可能会帮助您入门。但是您也可以查看foolproof,它有许多有用的验证属性可以解决您的需求,例如[RequiredIfTrue("IsMilestone") 应用于EndDate 属性
  • @StephenMuecke 您的评论,尤其是最后一部分,很好地回答了我的问题 - 您是否考虑将其添加为答案以便我接受?

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


【解决方案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还是不错的参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多