Validate Date in MM/dd/YYYY format in mvc

2019-01-27 10:21发布

问题:

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.

回答1:

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.



回答2:

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.


回答3:

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.



回答4:

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.