3

我需要以“hh:mm”(无秒)格式接收一些时间信息。属性定义如下:

[DataType(DataType.Time), DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm}")]
public TimeSpan SomeTimeProperty { get; set; }

服务器端验证按预期工作。但是,我无法让客户端验证工作,因为没有生成客户端验证规则。

我怎样才能让它工作?

4

1 回答 1

7

恐怕您需要走很长的路并为它创建一个自定义验证器属性。

public class TimeSpanValidationAttribute : ValidationAttribute, IClientValidatable
{
    public bool IsValid() {
        // Your IsValid() implementation here
    }

    // IClientValidatable implementation
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new TimeSpanValidationRule("Please specify a valid timespan (hh:mm)", "hh:mm");
        yield return rule;
    }
}

然后你需要编写 TimeSpanValidationRule 类:

public class TimeSpanValidationRule : ModelClientValidationRule
{
    public TimeSpanValidationRule(string error, string format)
    {
        ErrorMessage = error;
        ValidationType = "timespan";
        ValidationParameters.Add("format", format);
    }
}

这足以让 Html Helper为 html 输入框生成 adata-val-timespan="Please specify a valid timespan (hh:mm)"和 a 。data-val-timespan-format="hh:mm"

这两个值可以通过为“timespan”属性添加一个适配器到 javascript 不显眼的验证来“收获”。然后它将通过其相应的规则(将模仿服务器端规则)进行验证:

$.validator.unobtrusive.adapters.add('timespan', ['format'], function (options) {
    options.rules['timespan'] = {
        format: options.params.format //options.params picked up the extra data-val- params you propagated form the ValidationRule. We are adding them to the rules array.
    };
    if (options.message) { // options.message picked up the message defined in the Rule above
        options.messages['timespan'] = options.message; // we add it to the global messages
    }
});

$.validator.addMethod("timespan", function (value, el, params) {
    // parse the value and return false if not valid and true if valid :)
    // params.format is the format parameter coming from the ValidationRule: "hh:mm" in our case
});
于 2012-05-28T21:53:37.880 回答