对自定义属性执行客户端验证

rak*_*los 72 validation asp.net-mvc jquery razor asp.net-mvc-3

我创建了一个自定义验证属性:

public class FutureDateAttribute : ValidationAttribute
    {
        public override bool IsValid(object value) 
        {
            if (value == null|| (DateTime)value < DateTime.Now)
                return false;

            return true;
        }

    }
Run Code Online (Sandbox Code Playgroud)

如何使用jquery在客户端使用它?

Dar*_*rov 164

以下是如何继续:

首先定义自定义验证属性:

public class FutureDateAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        if (value == null || (DateTime)value < DateTime.Now)
            return false;

        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "futuredate"
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意它是如何实现IClientValidatable的.接下来我们写我们的模型:

public class MyViewModel
{
    [FutureDate(ErrorMessage = "Should be in the future")]
    public DateTime Date { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后一个控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            // intentionally put in the past
            Date = DateTime.Now.AddDays(-1)
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后一个观点:

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Date)
    @Html.TextBoxFor(x => x.Date)
    @Html.ValidationMessageFor(x => x.Date)
    <input type="submit" value="OK" />
}
Run Code Online (Sandbox Code Playgroud)

神奇发生的最后一部分是定义自定义适配器:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
    // we add a custom jquery validation method
    jQuery.validator.addMethod('greaterThan', function (value, element, params) {
        if (!/Invalid|NaN/.test(new Date(value))) {
            return new Date(value) > new Date($(params).val());
        }
        return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val()));
    }, '');

    // and an unobtrusive adapter
    jQuery.validator.unobtrusive.adapters.add('futuredate', { }, function (options) {
        options.rules['greaterThan'] = true;
        options.messages['greaterThan'] = options.message;
    });
</script>
Run Code Online (Sandbox Code Playgroud)

  • 精彩回答! (3认同)
  • 很好的例子.为了让客户端为我工作,适配器需要更改`return new Date(value)> new Date($(params).val()); `to`返回new Date(value)> new Date();`.**新日期($(params).val())**到**新日期()** (2认同)

jwa*_*zko 6

自从提出您的问题以来已经过了一段时间,但是如果您仍然喜欢元数据,并且您仍然对简化的替代方案持开放态度,则可以使用以下注释来解决您的问题:

[Required]
[AssertThat("Date > Now()")]
public DateTime? Date { get; set; }
Run Code Online (Sandbox Code Playgroud)

它适用于服务器和客户端,开箱即用。有关更多详细信息,请查看ExpressiveAnnotations库。