How to check whether the entered Date in Textfield is valid or not in Dart/Flutter?

Viewed 6553

Im taking day month and year in 3 Textfields but none of the DateTime property or function is providing the validation.

I have used DateTime.parse(str) to get the date but it adds the remaining months to the year if month field is entered with more then 12 same for days too.

bool isDate(String str) {
  try {
    DateTime.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}

I want if some one enters '20053050' to the string to be false not true. But this functions always return true !!!

enter image description here

5 Answers

There's simple method you can try now. Which is tryParse method. It simply returns null for invalid date format.

if(DateTime.tryParse(timeString) != null){
  DateTime date = DateTime.parse(timeString);
}

It seems to be an issue that the DateTime constructor allows invalid ranges: DateTime.parse should throw an error on invalid date...

Here is a workaround: How to check if a given Date exists in DART?

You could use it like this:

bool isValidDate(String input) {
  try {
    final date = DateTime.parse(input);
    final originalFormatString = toOriginalFormatString(date);
    return input == originalFormatString;
  } catch(e) {
    return false;
  }
}

String toOriginalFormatString(DateTime dateTime) {
  final y = dateTime.year.toString().padLeft(4, '0');
  final m = dateTime.month.toString().padLeft(2, '0');
  final d = dateTime.day.toString().padLeft(2, '0');
  return "$y$m$d";
}

Use parseStrict instead of just parse:

 DateFormat format = DateFormat("dd.MM.yyyy");
 DateTime dayOfBirthDate = format.parseStrict(value); //33.08.2001 - is invalid, 31.13.2001 - is invalid too

 DateFormat format = DateFormat("dd.MM.yyyy");
 DateTime dayOfBirthDate = format.parse(value); //33.08.2001 - will change to 2.09.2001 (same with months)

You could try to collect the date as a string (e.g. String _enteredDate) and have it converted to the date format you want using DateFormat with your formatting preference and parsing the string using DateTime.parse. E.g.:

_formattedDate = DateFormat('MM-dd-yyyy').format(DateTime.parse(_enteredDate))

If the user inputs and invalid date format, there should be an error which you can catch and alert.

bool isDate(String input, String format) {
  try {
    final DateTime d = DateFormat(format).parseStrict(input);
    //print(d);
    return true;
  } catch (e) {
    //print(e);
    return false;
  }
}

Check Date.

String inputDate = "2022-02-20"; 
if (isDate(inputDate, "yyyy-MM-dd")) {
    print("$inputDate Date Valid");
} else {
    print("$inputDate Date notValid");
}

"2022-02-20" Date Valid

"2022-02-30" Date notValid

Yann39 Answered from.

Related