0

I have declared a property in MVC info file like

  [Required(ErrorMessage = "End Date has not being entered")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        [RegularExpression(@"^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/]\d{4}$", ErrorMessage = "End Date should be in MM/dd/yyyy format")]
        public DateTime? ExpirationDate { get; set; }

But when I am entered a date in correct format like 5/13/2013. It stills show the errormessage that

End Date should be in MM/dd/yyyy format

What code I am missing or there is any other error with the above.

Abhishek
  • 377
  • 2
  • 8
  • 23

4 Answers4

3

You can't validate dates with regular expression, use DateTime.TryParseExact to convert the string into a DateTime object. Regex will always miss subtleties such as leap years, etc.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
1

You can't use the Regular expression to validate your DateTime in model, as Regex always validates the string values and when you apply it on DateTime it tries to convert in string. The string actually not in the format of MM/dd/YYYY and always throws the validation error.

Either you can choose one of the following way:

  1. Customize the error message in a resource file
  2. You can create a custom attribute derived from RegularExpressionAttribute and use that instead.
Community
  • 1
  • 1
Santosh Panda
  • 7,235
  • 8
  • 43
  • 56
0

The first part of the regexp does not allow for single digit month. You should change it to

(@"^([0]?\d|[1][0-2])/..."

Note the ? mark which means that the 0 is optional.

Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • (@"^([0]?\d|[1][0-2])\/([0-2]\d|[3][0-1])\/([2][01]|[1][6-9])\d{2}(\s([0-1]\d|[2][0-3])(\:[0-5]\d){1,2})?$" – Abhishek May 17 '13 at 11:00
  • sir i have placed these expression. but still shows the End Date should be in MM/dd/yyyy format – Abhishek May 17 '13 at 11:01
0

Check it out. I tried this not expecting it to work.

You can actually use a RegExp to validate a DateTime in MVC. This is my setup:


RegExp Attribute on property:

[RegularExpression(@"(^$)|(^\d{2}/\d{2}/\d{4})|(^((\d{1})|(\d{2}))/((\d{1})|(\d{2}))/(\d{4})\s((\d{1})|(\d{2}))[:]{1}((\d{1})|(\d{2}))[:]{1}((\d{1})|(\d{2}))\s((AM)|(PM)))", ErrorMessage = "Invalid Date")]


Enforced validation: Empty String, 1 or 2 digits for month/date in the MM/dd/yyyy format (e.g. 3/20/2015 or 03/20/2015 or 3/2/2015), C# Date (e.g. MM/dd/yyyy hh:mm:ss tt) - This is what allows ModelState.IsValid to return true for this property once the server converts it to a C# DateTime


TextBoxFor on view: @Html.TextBoxFor(x => x.DateOfWeightAndHeightCapture, "{0:MM/dd/yyyy}", new { @class = "form-control" })


This lets you have a DateTime property on a model, edited by a MVC TextBoxFor, that enforces client side and server side validation.

Chandler Zwolle
  • 1,635
  • 1
  • 11
  • 8