您可以为服务器端验证编写自定义模型绑定器:
public class DateModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null)
{
return null;
}
var format = bindingContext.ModelMetadata.EditFormatString ?? string.Empty;
format = format.Replace("{0:", string.Empty).Replace("}", string.Empty);
if (!string.IsNullOrEmpty(format))
{
DateTime date;
if (DateTime.TryParseExact(value.AttemptedValue, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
您将在其中注册Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime?), new DateModelBinder());
对于客户端验证,可以采用不同的技术。例如,您可以手动处理它:
<script>
$.validator.addMethod('myDate', function (value, element) {
// TODO: validate if the value corresponds to the required format
// and return true or false based on it
return false;
}, 'Please enter a date in the format yyMMdd');
$(function () {
// Attach the myDate custom rule to the #Something element
$('#Something').rules('add', 'myDate');
});
</script>