2012-05-28 46 views
3

我需要以格式「hh:mm」(,沒有秒)接收一些時間信息。屬性定義如下:客戶端驗證asp.net上的時間跨度mvc 3

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

服務器端驗證按預期工作。但是,我無法讓客戶端驗證 工作,因爲沒有生成客戶端驗證規則。

我該如何讓它工作?

+0

您是否具有強制客戶端生成的驗證規則的摘錄? –

+0

@Tomas,就是這個問題。它沒有生成用於驗證的屬性 – Fernando

+0

OK。我認爲你應該編輯帖子以澄清這是問題。 「沒有生成客戶端驗證規則」是比「我無法讓客戶端驗證工作」更好的問題描述。 ;) –

回答

6

恐怕你需要走很長的路線併爲它創建一個自定義驗證器屬性。

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輔助生成data-val-timespan="Please specify a valid timespan (hh:mm)"和HTML輸入框中data-val-timespan-format="hh:mm"

這兩個值可以通過添加一個適配器來「收穫」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 
});