gpt4 book ai didi

jquery - MVC.NET 自定义验证器不起作用

转载 作者:行者123 更新时间:2023-12-01 03:49:37 25 4
gpt4 key购买 nike

我想为 MVC.NET 框架编写一个自定义验证器,用于检查输入的日期是否是将来的日期。为此,我编写了以下类:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class InTheFutureAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} should be date in the future";

public InTheFutureAttribute()
: base(DefaultErrorMessage)
{
}

public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}

public override bool IsValid(object value)
{
DateTime time = (DateTime)value;

if (time < DateTime.Now)
{
return false;
}

return true;
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "wrongvalue"
};

return new[] { clientValidationRule };
}
}

并向我要检查的字段添加属性。

在“ View ”页面上,我通过以下方式创建输入字段:

<div class="editor-label-search">
@Html.LabelFor(model => model.checkIn)
</div>
<div class="editor-field-search-date">
@Html.EditorFor(model => model.checkIn)

<script type="text/javascript">
$(document).ready(function ()
{ $('#checkIn').datepicker({ showOn: 'button', buttonImage: '/Content/images/calendar.gif', duration: 0, dateFormat: 'dd/mm/yy' }); });
</script>
@Html.ValidationMessageFor(model => model.checkIn)
</div>

当我提交需要在验证器中检查属性代码的模型的 Controller 表单时,它会返回 false,但它不会显示错误,而是调用我的 Controller 的操作并向其发送无效模型。

我做错了什么吗?我该如何修复它?

最佳答案

您是否添加了客户端验证逻辑:自定义验证器和不显眼的适配器。如果没有,这是客户端逻辑:

//添加客户端验证器:

jQuery.validator.addMethod("wrongvalue",
function (value, element, param) {

var dateValue = $.datepicker.parseDate('dd/mm/yy', value); //use any date parser, if UI/Datepicker is not used

var now = new Date();
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

var isValid = dateValue >= today;
return isValid;
});

//添加一个不显眼的适配器:

jQuery.validator.unobtrusive.adapters.add("wrongvalue", [], function (options) {

options.rules["wrongvalue"] = true;
options.messages["wrongvalue"] = options.message;
});

关于jquery - MVC.NET 自定义验证器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10057885/

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