【问题标题】:Custom class validation not working?自定义类验证不起作用?
【发布时间】:2017-03-14 17:47:27
【问题描述】:

我目前正在使用 ASP.NET MVC 开发一个 Web 项目。我在其中有一个创建页面,它通过 SQL 服务器创建一个与数据库表对应的实体。我需要一些比简单的“必需”标签更好的验证,所以我选择使用自定义验证类。我对这个类的编码与我的其他自定义验证类完全一样,但由于某种原因,无论我尝试什么,这个类都不会在页面提交时触发。

视图模型:

public class MyViewModel {
     //my other properties         

      [ValidateCreateDate(ErrorMessage = "Date must be after or on today's date.")]
      public DateTime? RequestedDate { get; set; }
}

类:

public class ValidateCreateDateAttribute : RequiredAttribute
{
    private context db = new context();

    public override bool IsValid(object value) //breakpoint is never hit here
    {
      //code to check if it is valid or not
    }
}

查看:

@model context.MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("Create", "Data", FormMethod.Post))
 {
  <div class="row">    
    <div class="col-md-2">
      @Html.EditorFor(model => model.RequestedDate)
    </div>
    <div class="col-md-2">
      @Html.ValidationMessageFor(model => model.RequestedDate)
    </div>
    <div class="col-md-8">
      <button type="submit">Submit</button>
    </div>
 </div>
  }

<script type="text/javascript">
    $(function () {
        $("#RequestedDate").datepicker();
    });
</script>

【问题讨论】:

  • ClientValidationEnabled 和 UnobtrusiveJavaScriptEnabled 在配置中,是否包含用于不显眼的 js 文件?
  • 是的,这两个都启用了,我确实在我的实际代码中附加了不显眼的文件,感谢@Mackan
  • @EliHellmer 您的表单提交正确吗?它是否击中了“创建”操作方法?你的代码看起来不错
  • 是的,我相信我的操作方法代码很好,因为我有 2 个其他自定义验证类正在运行,它们都可以正常工作。真奇怪
  • 刚刚复制并粘贴了您的代码,它对我有用。

标签: c# html asp.net-mvc validation


【解决方案1】:

按照评论的建议做

ModelState.IsValid

并返回一个错误,解释如下:https://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

派生ValidationAttribute而非RequiredAttribute的验证实现:

 namespace YourProject.Common.DataAnnotations
    {
        [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
        public sealed class ValidateCreateDateAttribute : ValidationAttribute
        {
            private const string _defaultErrorMessage = "Date is requierd, value most be after or on today's date.";
            public ValidateCreateDateAttribute()
            {
                if (string.IsNullOrEmpty(ErrorMessage))
                {
                    ErrorMessage = _defaultErrorMessage;
                }
            }
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                if (value != null)
                {
                    Type type = value.GetType();
                    if (type.IsPrimitive && (type == typeof(DateTime) || type == typeof(DateTime?)))
                    {
                        var checkDate = Convert.ToDateTime(value);
                        //in UTC, if you are using timezones, use user context timezone
                        var today = DateTime.UtcNow.Date;
                        //compare datetimes
                        if (DateTime.Compare(checkDate, today) < 0)
                        {
                            return new ValidationResult(ErrorMessage);
                        }
                        //success
                        return ValidationResult.Success;
                    }
return new ValidationResult("Cannot validate a non datetime value");
                }
                //if value cannot be null, you are using nullable date time witch is a paradox
                return new ValidationResult(ErrorMessage);
            }
        }
    }

【讨论】:

  • 谢谢! @SilentTremor
猜你喜欢
  • 2013-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多