如何更改客户端验证消息?

时间:2015-03-25 10:28:04

标签: javascript jquery asp.net-mvc validation unobtrusive-validation

我的模型中有一个datetime字段应该验证:

[DateValidation(ErrorMessage = "AccDate should be greater or equal to the current date")]
public DateTime? AccDate { get; set; }

DateValidation是一个手工制作的类:

public class DateValidation : ValidationAttribute, IClientValidatable
{
    public DateValidation()
    {

    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext.ObjectInstance is OrderModel)
        {
            var model = validationContext.ObjectInstance as OrderModel;

            if (model.EndDate == null && model.AccDate.HasValue)
            {
                if (model.RecDate.HasValue && model.AccDate.Value < model.RecDate.Value)
                {
                    var errorMessage = "AccDate should be greater than the RecDate";
                    return new ValidationResult(errorMessage);
                }

                if (model.AccDate.Value < DateTime.Now)
                {
                    var errorMessage = "AccDate should be greater or equal to the current date";
                    return new ValidationResult(errorMessage);
                }
            }
        }

        return ValidationResult.Success;
    }

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

我还有一个datevalidator.js文件:

$.validator.unobtrusive.adapters.add("datevalidator", [], function (values) {
    values.rules['datevalidator'] = {
    };
    values.messages['datevalidator'] = values.message;
});

$.validator.addMethod("datevalidator", function (value, element, params) {
    if (element.id == "AccDate") {    
        if (value) {
            var nowDate = new Date($.now());
            var accDate = new Date(value);
            var recDate = new Date($("#RecDate").val());

            if (accDate <= recDate) {
                return false;
            }

            if (accDate < nowDate) {
                return false;
            }

            return true;
        }
    }   
});

本身一切正常。验证阻止我做出无法解决的行动但是我有一个问题

我收到的错误消息始终等于:"AccDate should be greater or equal to the current date"

根据我的理解,它发生的原因是[DateValidation(ErrorMessage = "AccDate should be greater or equal to the current date")]rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());。到目前为止,我无法改变它。

加载页面后,我收到包含此错误消息的data-val-datevalidator $("#AccDate")属性。我试图改变它并使每种情况都不同(类似于ValidationResult返回的内容):

if (accDate <= recDate) {
    $("#AccDate").attr("data-val-datevalidator", "AccDate should be greater than the RecDate");
    return false;
}

但根本没有反应(属性值已经改变,但显示错误信息仍然是旧的)。

如何在datevalidator.js中为不同的错误消息更改错误消息?

0 个答案:

没有答案