I would like to check whether a date entered by the user in DateTime format is valid or not, to convert it if it is valid and to display an exception if it is not
The problem is that Dart internally already converts that date for me into a valid date, example
The month of september has only 30 days and the test below returns false as dart converts the date 09/31/2023 to 10/01/2023 which is a valid date
expect(format.validDateTime(DateTime(2023, 9, 31)), false); // the test was supposed to return false, but it returns true
Is there a way to prevent this Dart conversion behavior and keep the date entered by the user?
If you want to parse it yourself, you can probably take the text before you convert it to DateTime.
Alternatively, use
parseStrictwith whatever format you find most useful:That will indeed throw an exception when you try:
What you cannot do however, is make a
DateTimesay "2023-02-31". Because it does not save it that way internally. It saves the milliseconds from a point in time in 1970, so whatever you pass it along, it will always be a valid date once transformed back from those milliseconds into days and months.