我目前正在使用ASP.NET MVC开发一个Web项目。我有一个创建页面,它通过SQL服务器创建一个对应于数据库表的实体。我需要一些验证,而不仅仅是'required'标签,所以我选择使用自定义验证类。我编写的类与我的其他自定义验证类完全相同,但是出于某种原因,无论我尝试什么,这个类都不会在页面提交时触发。
视图模型:
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>
查看:
{{1}}
答案 0 :(得分:0)
作为评论推荐
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);
}
}
}