客户端验证asp.net mvc 3上的时间跨度

Fer*_*ndo 3 validation asp.net-mvc timespan custom-formatting

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

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

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

我怎样才能使它工作?

Tal*_*ris 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你需要编写TimeSpanValidationRule类:

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

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

可以通过向"timepan"属性的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
});
Run Code Online (Sandbox Code Playgroud)