gpt4 book ai didi

jquery - MVC 自定义验证 : compare two dates

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

我创建了一个自定义 ValidationAttribute 来比较两个日期并确保第二个日期大于第一个:

public sealed class IsDateAfter : ValidationAttribute, IClientValidatable
{
private readonly string testedPropertyName;
private readonly bool allowEqualDates;

public IsDateAfter(string testedPropertyName, bool allowEqualDates = false)
{
this.testedPropertyName = testedPropertyName;
this.allowEqualDates = allowEqualDates;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.testedPropertyName);
if (propertyTestedInfo == null)
{
return new ValidationResult(string.Format("unknown property {0}", this.testedPropertyName));
}

var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);

if (value == null || !(value is DateTime))
{
return ValidationResult.Success;
}

if (propertyTestedValue == null || !(propertyTestedValue is DateTime))
{
return ValidationResult.Success;
}

// Compare values
if ((DateTime)value >= (DateTime)propertyTestedValue)
{
if (this.allowEqualDates)
{
return ValidationResult.Success;
}
if ((DateTime)value > (DateTime)propertyTestedValue)
{
return ValidationResult.Success;
}
}

return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessageString,
ValidationType = "isdateafter"
};
rule.ValidationParameters["propertytested"] = this.testedPropertyName;
rule.ValidationParameters["allowequaldates"] = this.allowEqualDates;
yield return rule;
}

日历条目类:...

public virtual DateTime StartDate { get; set; }

[IsDateAfter("StartDate", true, ErrorMessage="End date needs to be after start date")]
public virtual DateTime EndDate { get; set; }

查看:

$.validator.unobtrusive.adapters.add(
'isdateafter', ['propertytested', 'allowequaldates'], function (options) {
options.rules['isdateafter'] = options.params;
options.messages['isdateafter'] = options.message;
});
$.validator.addMethod("isdateafter", function(value, element, params) {
alert(params.propertytested);
var startdatevalue = $('input[name="' + params.propertytested + '"]').val();
if (!value || !startdatevalue) return true;
return (params.allowequaldates) ? Date.parse(startdatevalue) <= Date.parse(value) : Date.parse(startdatevalue) < Date.parse(value);
}, '');

CalendarEntry 没有包含在另一个类中时,这可以正常工作。但是,当我使用这样的 View 模型时:

    public class TrainingDateEditViewModel
{
#region Properties

/// <summary>
/// Gets or sets CalendarEntry.
/// </summary>
public CalendarEntry CalendarEntry { get; set; }
....

客户端验证不再有效,因为生成的 html 输出是这样的:

<input type="text" value="" name="CalendarEntry.EndDate" id="CalendarEntry_EndDate" data-val-isdateafter-propertytested="StartDate" data-val-isdateafter-allowequaldates="True" data-val-isdateafter="End date needs to be after start date" data-val="true">

data-val-isdateafter-propertytested="StartDate" and IT SHOULD BE: "CalendarEntry.StartDate".

我该怎么做才能知道绑定(bind)到“CalendarEntry.StartDate”rule.ValidationParameters["propertytested"] = this.testedPropertyName;//这里应该是全名???如何??

谢谢

最佳答案

您需要修改您的客户端脚本来检查被测试元素的前缀,并将前缀(如果有)添加到您的选择器中,如下所示:

$.validator.addMethod("isdateafter", function(value, element, params) {
var parts = element.name.split(".");
var prefix = "";
if (parts.length > 1)
prefix = parts[0] + ".";
var startdatevalue = $('input[name="' + prefix + params.propertytested + '"]').val();
if (!value || !startdatevalue)
return true;
return (params.allowequaldates) ? Date.parse(startdatevalue) <= Date.parse(value) :
Date.parse(startdatevalue) < Date.parse(value);
});

关于jquery - MVC 自定义验证 : compare two dates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7025198/

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