MVC2 DateTime的客户端验证?

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属性时所做的事情.

你有什么建议?

maa*_*nba 4

如上所述,请遵循 Phil Haack 关于自定义验证的帖子:http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

我会这样做:


  1. 添加一个“DateFormatAttribute”类,如下所示:

    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)
  1. 添加一个“DateFormatValidator”类,如下所示:

    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)
  1. 在 Global.asax.cs 中的某个位置注册上述类:

    DataAnnotationsModelValidatorProvider
        .RegisterAdapter(typeof(DateFormatAttribute), typeof(DateFormatValidator));
Run Code Online (Sandbox Code Playgroud)
  1. 在客户端添加验证功能。请注意,这必须根据用户的区域设置来实现。以下是荷兰语(nl-NL、nl-BE)客户端验证函数:

    /*
     * 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)

这应该涵盖一些事情...