时间跨度在asp.net MVC 3客户端验证 [英] Client side validation of a timespan on asp.net mvc 3

查看:129
本文介绍了时间跨度在asp.net MVC 3客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要接受的格式一段时间信息HH:MM(否秒)。该物业的定义是这样的:

I need to receive some time information in the format "hh:mm" (no seconds). The property is defined like this:

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

服务器端验证按预期工作。但是,我不能得到的客户端验证
因为没有生成客户端验证规则来工作。

The server side validation works as expected. However, I can't get the client side validation to work as no client-side validation rules are generated.

我怎样才能使它工作?

推荐答案

我怕你会需要去冤枉路并为它创建一个定制的验证属性。

I am afraid you will need to go the long route and create a Custom validator attribute for it.

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类:

Then you need to write the TimeSpanValidationRule class:

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

这是足以让HTML辅助生成一个数据-VAL-时间跨度=请指定一个有效的时间内(HH:MM)数据-VAL-时间跨度格式=HH:MM。的HTML输入框

This is enough to get the Html Helper generate a data-val-timespan="Please specify a valid timespan (hh:mm)" and a data-val-timespan-format="hh:mm" for the html input box.

通过添加适配器不显眼的JavaScript验证,为时间跨度属性这两个值可以收获。

This two values can be "harvested" by adding an adapter to javascript unobtrusive validation for the "timespan" attribute. It will then be validated by its corresponding rule (which will mimic the server side rule):

$.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
});

这篇关于时间跨度在asp.net MVC 3客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆