gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:26:04 25 4
gpt4 key购买 nike

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

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

return true;
}

}

如何使用 jquery 使其在客户端也能正常工作?

最佳答案

下面是如何进行:

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

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

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

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

然后是一个 Controller :

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

最后是一个 View :

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

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

<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>

关于jquery - 对自定义属性执行客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4747184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com