MVC自定义客户端验证日期应大于或等于今天

时间:2015-04-08 14:48:28

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

我正在使用ASP.NET MVC4,我的要求是所选日期应大于或等于今天的日期。我创建了一个自定义验证属性。它适用于服务器端,但不适用于客户端。到目前为止,这是我的代码:

[AttributeUsage(AttributeTargets.Property)]
public class DateGreaterThanTodayAttribute : ValidationAttribute, IClientValidatable
{
    private readonly bool allowTodayDate;

    public DateGreaterThanTodayAttribute( bool allowTodayDate = false)
    {
        this.allowTodayDate = allowTodayDate;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null || !(value is DateTime))
        {
            return ValidationResult.Success;
        }
        // Compare values

        if ((DateTime)value > DateTime.Today)
        {
            return ValidationResult.Success;
        }

        if (this.allowTodayDate && (DateTime)value == DateTime.Today)
        {
            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 = "istodaydate"
        };

        rule.ValidationParameters["allowtodaydate"] = this.allowTodayDate;
        yield return rule;
    }
}

我的客户端代码是:

// Greater Than Today dates
$.validator.unobtrusive.adapters.add(
        'istodaydate', ['allowtodaydate'], function (options) {
            options.rules['istodaydate'] = options.params.allowtodaydate;
            options.messages['istodaydate'] = options.message;
        });

$.validator.addMethod("istodaydate", function (value, element, param) {
    if (!value) return true;
    return (param.allowtodaydate) ?
        $.datepicker.parseDate('dd/mm/yy', new Date()) <= $.datepicker.parseDate('dd/mm/yy', value) :
        $.datepicker.parseDate('dd/mm/yy', new Date()) < $.datepicker.parseDate('dd/mm/yy', value);
}, '');

我的模型是

    [DateGreaterThanToday(true, ErrorMessageResourceType = typeof(APMS.Resources.Errors), ErrorMessageResourceName = "StartDateAfterEndDate")]
    [Required(ErrorMessageResourceType = typeof(Resources.QCP.Resource), ErrorMessageResourceName = "SurveyInterval_FromDateRequired")]
    public DateTime FromDate { get; set; }

0 个答案:

没有答案