Jos*_*osh 8 javascript datetime client-side-validation asp.net-mvc-2-validation asp.net-mvc-2
您建议在MVC中验证客户端的DateTime有哪些方法?
比方说,我有一个命名属性的模型DateOfBirth是一个DateTime,像这样.
public class UserModel
{
[DataType(DataType.Date)]
public DateTime DateOfBirth {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
在View上,我有一个简单的
<%: Html.LabelFor(model=>model.DateOfBirth) %>
<%: Html.EditorFor(model=>model.DateOfBirth) %>
<%: Html.ValidationMessageFor(model=>model.DateOfBirth) %>
<input type="submit" value="Submit" />
Run Code Online (Sandbox Code Playgroud)
我可以使用Microsoft MVC验证或jQuery验证.如何让DateTime验证客户端?
我意识到所有DataTypeAttribute都提供了格式化提示,并没有真正做任何验证(它将该部分留给了ModelBinder).
基本上我想复制ModelBinder在尝试将发布的值放入模型的DateOfBirth属性时所做的事情.
你有什么建议?
如上所述,请遵循 Phil Haack 关于自定义验证的帖子:http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
我会这样做:
public class DateFormatAttribute : ValidationAttribute {
public override bool IsValid(object value) {
if (value == null) {
return true;
}
// Note: the actual server side validation still has to be implemented :-)
// Just returning true now...
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
public class DateFormatValidator : DataAnnotationsModelValidator
{
string message;
public PriceValidator(ModelMetadata metadata, ControllerContext context
, DateFormatAttribute attribute)
: base(metadata, context, attribute)
{
message = attribute.ErrorMessage;
}
public override IEnumerable GetClientValidationRules()
{
var rule = new ModelClientValidationRule {
ErrorMessage = message,
ValidationType = "date" // note that this string will link to the JavaScript function we'll write later on
};
return new[] { rule };
}
}
Run Code Online (Sandbox Code Playgroud)
DataAnnotationsModelValidatorProvider
.RegisterAdapter(typeof(DateFormatAttribute), typeof(DateFormatValidator));
Run Code Online (Sandbox Code Playgroud)
/*
* Localized default methods for the jQuery validation plugin.
* Locale: NL
*/
jQuery.extend(jQuery.validator.methods, {
date: function(value, element) {
return this.optional(element) || /^\d\d?[\.\/-]\d\d?[\.\/-]\d\d\d?\d?$/.test(value);
}
});
Run Code Online (Sandbox Code Playgroud)
这应该涵盖一些事情...
| 归档时间: |
|
| 查看次数: |
3303 次 |
| 最近记录: |