0

我的要求是允许用户以“yymmdd”格式输入日期,在文本字段中总共输入 6 位数字。

该表单通过不显眼的 ajax 发布到 mvc3 控制器/操作,该控制器/操作通过 Entity Framework 4.1 将其保存到 mysql 数据库。如果我以所需的“yymmdd”格式输入日期,那么它会将日期保存为空。

我的问题是如何使用自定义日期格式,保留客户端和服务器端验证并成功地将这个日期保存到数据库中。我很高兴使用正则表达式进行验证,但需要帮助来解析自定义日期格式。

模型中的日期指定为

public class CustomDate {
  [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyMMdd}")]
  //[RegularExpression(@"^[0-9]{6}$")]
  public DateTime? Something { get; set; } 
}

支持表单的操作具有以下签名。

public JsonResult NewClaim(CustomDate d) {
db.CustomDate.Add.(d);
db.SaveChanges();
}
4

1 回答 1

1

您可以为服务器端验证编写自定义模型绑定器:

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>
于 2011-09-19T13:04:00.470 回答