Custom date input format in .net mvc3 entity framework webapp?
I have the requirement that users should be allowed to enter dates in the format "yymmdd", 6 digits in total in a textfield.
The form is posted via unobtrusive ajax to a mvc3 controller/action which persists this to a mysql database via Entity Framework 4.1. Unfortionently it saves the date as a null if I enter the date in the desired "yymmdd" format.
My question is how do I use a custom date format, retain client- and serverside validation and successfully persist this date into the database. I'm happy to use a regexp for the validation but need help to parse the custom date format.
The date in the modelis specified as
public class CustomDate {
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyMMdd}")]
//[RegularExpression(@"^[0-9]{6}$")]
public DateTime? Something { get; set; }
}
The action backing the form have the following signature.
public JsonResult NewClaim(CustomDate d) {
db.CustomDate.Add.(d);
db.SaveChan开发者_运维问答ges();
}
You could write a custom model binder for the server side validation:
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);
}
}
which you would register in Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime?), new DateModelBinder());
For the client side validation there are different techniques that could be employed. For example you could handle it manually:
<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>
精彩评论