自定义类验证不起作用

本文关键字:不起作用 验证 自定义 | 更新日期: 2023-09-27 18:15:44

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

Viewmodel:

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>

自定义类验证不起作用

按注释的建议做

状态。IsValid

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

验证实现派生ValidationAttribute not requireattribute :

 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);
            }
        }
    }