What is the best way to analyze dates in a binder

Is a good approach in a connecting device using code like this:

TryParseDate(result.AttemptedValue, format, out parsedDate) 

And then the β€œformat” is a variable with a different (specific client) date format. Like 12/31/2013 or 12/31/2013 or others.

I have a big problem with format binding, because if the user puts a date with only one digit, for example: 1/1/2014, it will not be analyzed, because in the formats of the allowed formats: dd / MM / yyyy I know that this can be solved by replacing this format with d / M / yyyy, and then it works for both cases, but is this a good approach or is it dangerous?

Thank you in advance!

+6
source share
1 answer

I would recommend leaving the default model binding to do the job, it does a good job of this and will solve localization problems (i.e. different date formats for different locales) for you.

Note that there will always be restrictions on how the user can enter a date (you do not allow them to enter yyyy-MM-dd , for example, although this is a valid date format). Your own middleware code will not change because it provides a format.

I would suggest that your goal should be to allow users to enter dates in a format that would be most common for them (e.g. dd/MM/yyyy in the UK or Spain, MM/dd/yyyy in the USA, etc. d.). This will deal with most cases. If you need to serve users in different locales, the mediator will do all this for you by default, as long as you set the flow culture for the user session:

 string cultureCode = "en-GB"; //retrieve eg. from user profile Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureCode) 

If you want to help users entering dates in other formats, just put a tip on your page explaining the expected format.

If you really have to accept multiple formats for each locale, you will need to write a custom mediator and you might want to try passing an array of acceptable formats for each locale you are dealing with.

+1
source

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


All Articles