長い道のりをたどって、そのためのカスタムバリデーター属性を作成する必要があると思います。
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"
この 2 つの値は、"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
});