Confirm date in MM / dd / YYYY format in mvc

I declared a property in the 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 entered the date in the correct format, for example, 13/13/2013. It still shows an error that

 End Date should be in MM/dd/yyyy format 

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

0
source share
4 answers

You cannot check dates with regex, use DateTime.TryParseExact to convert a string to a DateTime object. Regex will always skip subtleties such as leap years, etc.

+3
source

You cannot use a Regular expression to validate your DateTime in a model, since Regex always checks string values, and when you use it in DateTime, it tries to convert the string. The string is actually not in MM / dd / YYYY format and always throws a validation error.

You can choose one of the following methods:

+1
source

The first part of the regular expression does not allow a single month. You have to change it to

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

Pay attention to the label ? , which means 0 is optional.

0
source

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

In fact, you can use RegExp to check for DateTime in MVC . This is my setup:


RegExp attribute 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 ")]


Forced check: Empty line, 1 or 2 digits for the month / date in the format MM / dd / yyyy (e.g. 3/20/2015 or 03/20/2015 or 3/2/2015), C # date (e.g. MM / dd / yyyy hh: mm: ss tt) is what allows ModelState.IsValid to return true for this property as soon as the server converts it to C # DateTime


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


This allows you to have the DateTime property on the model edited using MVC TextBoxFor, which provides client and server side validation.

0
source

Source: https://habr.com/ru/post/1014665/


All Articles