I'm having a terrible time adding a date to a view. I want the user to be able to type in a date like 6/30/15 or 6/30/2015, but the validation keeps failing if I use the 2 digit date. I've tried to "tell" MVC to accept a two digit date, but it always fails. Can someone explain how to get this right?
My view is set up like this (including just the troublesome date field for brevity):
@model Models.CompanyContracts
@Html.EditorFor(m => m.BegDate)
I started out with a simple model with a date field defined like this:
public DateTime? BegDate { get; set; }
I got an error saying "The field BegDate must be a date" when I entered the date as 6/30/15 or 06/30/15; I did not get the error when I entered 6/30/2015 or 06/30/2015.
So I tried to add a type and display attribute as describe Here: Format datetime in asp.net mvc 4
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:M/d/yy}", ApplyFormatInEditMode = true)]
I get the same error trying to enter 6/30/15. I tried several different formats, including a datatype and not a displayformat, including a displayformat and not a datatype, but I get the "The field BegDate must be a date" error everytime.
I tried a regular expression validation and it also failed (both the MVC validation and the regular expression; obviously the regex I got from http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5&AspxAutoDetectCookieSupport=1 needs some work):
[RegularExpression(@"^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$", ErrorMessage = "Invalid Date")]
public DateTime? BegDate { get; set; }
Can someone tell me how to get MVC to accept entering dates with 2 or 4 digits?
One other note, no external date pickers. I need to get this working with a simple entering of text. Once I can prove that can be done, my boss might allow me to spend some time figuring out a date picker. Thanks!
-- Update 7/20/15 -- Anyone have suggestions for this? I haven't found anything online that's helped me. I'd appreciate any feedback at this point to give me somewhere else to look for a solution.
-- Update 7/29/15 -- Still looking for suggestions. Any ideas at all?