Date Fails Client and Server Side Validation Using ASP.NET MVC 3 Data Annotations - asp.net-mvc-3

In all my projects, I have jQuery date pickers that format the date dd-MMM-yyyy
which both users worldwide and the DateTime.parse method understand perfectly - sadly this does not appear to be the case for data annotation validation! I have my data annotation as below:
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d-MMM-yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "You must enter a date of birth.")]
public DateTime dob { get; set; }
And my form refuses to submit with the error as below:
Does anyone know how I can make it validate, accept and modelbind a date value in this format?

You could write a custom model binder for the DateTime type as I have shown here that will use the format defined in the [DisplayFormat] attribute when parsing back a DateTime field from the request. By the default the model binder uses the CultureInfo setting of the current thread or the value you have configured in the <globalization> element of your web.config. If you set it to auto, then ASP.NET will use the client Accept-Language request header to adjust the culture info.

Related

How to validate date properly in mvc 3?

I want to validate the date properly.If Iam entering the date as 21-2-198 instead of 21-2-1988
.The date is not validating properly in Mvc3.I used Regex for this but didn't be useful.Is any other method to validate the date including the year in MVC model.Following is the code i written in the model
[Required(ErrorMessage = "Activation date is required")]
[Display(Name = "Activation date")]
[RegularExpression(#"/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/", ErrorMessage = "Enter proper date")]
public DateTime? ActivationDate { get; set; }
you should be able to get validation by using the [DataType(DataType.Date)] attribute instead of your regular expression. Note that this Annotation is locale agnostic... i.e. 21-2-1988 and 2-21-1998 will both validate.
Iam entering the date as 21-2-198 instead of 21-2-1988 .The date is not validating properly in Mvc3.
It seems to me that you need a CustomValidator that prevents user to enter a date out of specific range.
ASP.NET MVC 3 Custom Validation using Data Annotations presents a Validator for this purpose.

Telerik asp.net for MVC datepicker format in grid related issue

I have specified date format as dd/mm/yyyy for telerik datepicker. However, it is recognized as mm/dd/yyyy only. For example, if i enter date as 18/10/2012 error on saving record is thrown as date format is not valid as date entered here as 18 is treated as month. I have defined view for date as:
#model DateTime?
#(Html.Telerik().DatePickerFor(m => m)
.Name(ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty))
.Format("dd/MM/yyyy")
.HtmlAttributes(new { id = ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty) + "_wrapper" })
.InputHtmlAttributes(new {style="width:160px;"}))
And in model validation for date field is defined as:
[Required(ErrorMessage = "Date Required")]
[DataType(DataType.Date)]
public DateTime? DATE_CALL { get; set; }
Also, in grid has defined column as:
col.Bound(r => r.DATE_CALL).Format("{0:dd/MM/yyyy}").Title("DATE_CALL").Width(170);
So, can't figure out what the error is? Any help will be appreciated.
use the following to set your date format before saving to the database:
DateTime.ParseExact(<yourDate>, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);

Automatical bind of datetime fields in MVC3

I have a page with many date fields, which can be dynamically added on client side. I have a DatTime? property on editor template for this field:
[Display(Name = "Bar Admission Date")]
public DateTime? AdmissionDate { get; set; }
When I'm submitting a form I get a null data in AdmissionDate field because binder doesn't know the format of the field.
I have 2 ideas of how t oovercome this issue:
Make a string field in model and parse it on a server side. Simple and pretty quick.
Write a custom model binder for date fields. I don't like this solution because I don't know the keys for all fields that I will use.
Is there better solution? I searched how can I overload TextboxFor method in order to pass it a culture, but I didn't find
Sounds like you should use an enumerable (IList/ICollection) of DateTime?. Phil Haacked has a good article on model binding to a list (even when the number of items is dynamic).
Updated
As for the formatting problem, I would look at how to set the culture for the project/model binder.

JQuery Validation and MVC 3. How to change date format

I'm a newbie to MVC 3 and JQuery Validation so any help I can get here will be very much appreciated.
My devleopment platform is .NET MVC 3 website. I'm using the built in unobtrusive javascript for form validation. Is there a way to change the date to a different format for a valid date. As far as I can tell, the valid format is dd/mm/yy. Is it possible to change the valid date format to something like "Apr 3, 2012"?
My view model has a field
[Required]
DateTime OrderDate { get; set; }
I know that MVC 3 is using jquery validation under the hood so I'm thinking the solution will require a change to jquery validate and also not sure how to hook it up to MVC so it works like all the other built in data validations using data annotations.
Thank you.
When you use client side validation for date, you have to override the jQuery validation for date as well.
$.validator.methods.date = function (value, element) {
return this.optional(element) || Globalize.parseDate(value, "MMM dd, yyyy") !== null;
}
You have to reference the Globalize library and the appropriate culture in your HTML head. Download from https://github.com/jquery/globalize.
If you wanted to change the format of Order Date you would do so with the DisplayFormat annotation:
[DisplayName("Order Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy}")]
[Required]
DateTime OrderDate { get; set; }
Where the DataFormatString is your desired date time format.

In MVC3 is it possible to have multiple EditorTemplates for the same type?

I have some DateTime fields on my MVC model classes - some which require a Date as input and others that require a Time as input - but both are DateTime properties.
Is it possible to have an EditorTemplate for DateTime that somehow produces a date picker to properties that are meant to be dates, and a time picker for properties that are meant to be times?
Yes, here is one way:
In ~/Views/Shared/EditorTemplates (or ~/Views/Shared/DisplayTemplates, create template files that use your favourite view engine (example uses Razor/C#)
file Date.cshtml
replace this with a real date picker
file Time.cshtml
replace this with a real time picker
Then, in your model:
[UIHint("Date")]
public DateTime DateProperty { get; set; }
[UIHint("Time")]
public DateTime TimeProperty { get; set; }
The UIHint attribute name has to match the file name of your template, and UIHint is in System.ComponentModel.DataAnnotations, so you will need the appropriate using statement/assembly reference if you don't have it already.
Alternatively, use a TimeSpan to represent your times - that is what DateTime returns for its TimeOfDay property...

Resources