Unobtrusive validation/jQuery 客户端验证输入的日期早于当前日期

Unobtrusive validation/jQuery client-side Validate that Date entered is more than the current date

我有一个日期字段,我想验证这个日期是否早于今天的日期。

<script>
    jQuery.validator.addMethod("currentdate", function (value, element) {
        return Date.parse(value) > Date.parse(new Date());
    }, jQuery.validator.format("Date invalid"));
</script>

    @Html.LabelFor(m=>m.booking.Date)
    @Html.TextBoxFor(m => m.booking.Date, new { @class = "form-control", @id="Date" })
    @Html.ValidationMessageFor(m=>m.booking.Date)

采取什么方法?我该如何构建我的 html 助手?

假设下面的表单带有一个名为 Date 的文本框:

@model TestFormViewModel

@{
    ViewBag.Title = "Index";
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

<h2>Test Form</h2>

@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.Date)
    @Html.ValidationMessageFor(x => x.Date)
    <input type="submit" value="Submit" />
}

@section scripts {  
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate-vsdoc.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script src="~/Scripts/validationrule.js"></script>
}

简单的控制器动作:

[HttpPost]
public ActionResult Index(TestFormViewModel requestResponsemodel)
{
    return View(requestResponsemodel);
}

一个 JavaScript 文件包含在名为 validationrule.js 的页面中:

$.validator.unobtrusive.adapters.add("currentdate", [], function (options) {
    options.rules['currentdate'] = options.params;
    if (options.message) {
        options.messages['currentdate'] = options.message;
    }
});

$.validator.addMethod("currentdate",
    function (value, element, other) {

        return Date.parse(value) > Date.parse(new Date());
    }
);

DateValidationAttribute.cs 包含您的服务器端验证:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class CurrentDateValidationAttribute : ValidationAttribute, IClientValidatable
{

    // Default error message, can be overridden in the use of the attribute on your model
    public CurrentDateValidationAttribute() : base("The date must be later than the current date.")
    {
    }

    public override bool IsValid(object value)
    {
        var dateToValidate = (DateTime)value;
        return dateToValidate > DateTime.UtcNow;
    }

    // Client-Side validation 
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientCurrentDateValidationRule("The date must be later than the current date.");
        yield return rule;
    }
}

... 和一个 ModelClientValidationRule,它会将错误消息放入 Html 助手 (@Html.TextBoxFor()) 的输出中,由 JavaScript 在客户端获取验证码:

public class ModelClientCurrentDateValidationRule : ModelClientValidationRule
{
    public ModelClientCurrentDateValidationRule(string errorMessage)
    {
        ErrorMessage = errorMessage;
        ValidationType = "currentdate";
    }
}

使用分配给您的模型的自定义验证属性进行验证的模型,在本例中为 Date 属性:

public class TestFormViewModel
{
    [CurrentDateValidation(ErrorMessage = "The date must be later than the current date.")]
    public DateTime Date { get; set; }
}

当字段中包含的日期早于当前日期时,您的日期字段将在客户端站点上验证为无效,如下所示: