Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 343
Rishabh Bhardwaj Avatar asked Oct 10 '19 19:10

Rishabh Bhardwaj


People also ask

How do you add validation to TextField in Flutter?

In this example, learn how to add validation to a form that has a single text field using the following steps: Create a Form with a GlobalKey . Add a TextFormField with validation logic. Create a button to validate and submit the form.

How to validate textformfiled or textfield data with Dart regex in flutter?

isUUID - check if the string is a UUID (version 3, 4 or 5). matches - check if string str matches the Regex pattern. In this way, you can validate TextFormFiled or TextField data with Dart Regex and package in Flutter App.

How do I validate a text field in flutter?

TextFormField is also a better option for validation. Flutter handles error text itself, so we don’t require to use variable _validate. It will check at runtime whether you satisfied the condition or not. Note: The user must add at least one character to get this error message. Using a TextFormField with a validator.

How to validate data without using regex in flutter?

if(fname.text.length > 10){ //length of textfield with controller "name" has more than 10 characters. } Furthermore, you can validate data easily without using Regex. For that, add validators flutter packag e to your dependency by adding the following line in pubspec.yaml file: contains - check if the string contains the seed.

What is the difference between _formkey and _datecontroller?

_formKey is used as a global identifier to our form that we will use when submitting and validating the form _dateController is a TextEditingController that we use to manually change the text inside the date text field that we are going to create selectedDate is used to store the date that is returned from the date picker


1 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);
}
like image 151
NaKib Avatar answered Oct 13 '22 23:10

NaKib