不显眼的验证/ jQuery客户端验证输入的日期是否超过当前日期

时间:2017-07-03 09:17:16

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

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

<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助手?

1 个答案:

答案 0 :(得分:0)

假设以下表单带有一个名为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);
}

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

$.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; }
}

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

validation for field before the current date