Braken Mohamed
Braken Mohamed

Reputation: 322

Flutter How to validate DateTime isn't null

I'd like to validate the date entered by the user, so the date shouldn't be null how to add the validation ?!! Here my code I want the date different of null otherwise display a message to the user

TextFormField(
              readOnly: true,
              controller: dateController,
              validator: (value) {
                if (value.length != null) {
                  return 'no';
                }
              },
              decoration: InputDecoration(hintText: 'Pick your Date'),
              onTap: () async {
                var date = await showDatePicker(
                    context: context,
                    initialDate: DateTime.now(),
                    firstDate: DateTime(1900),
                    lastDate: DateTime(2100));
                dateController.text = date.toString().substring(0, 10);
              },
            ),

Upvotes: 1

Views: 979

Answers (2)

Tasnuva Tavasum oshin
Tasnuva Tavasum oshin

Reputation: 4750

date ?? DateTime.now();

date is Your Date. ?? will check its null or not then if its null it will pick DateTime.now();

Upvotes: 0

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12363

validator: (value) {
   if (value.isEmpty) 
     return "Please pick a date";
 }

This is assuming that you did not give an initial value to your dateController.

If you did give it an initial value, for example,

dateController.text = "Please pick a date"

if (dateController.text == "Please pick a date") 
         return "Please pick a date";

This will check if the value of the controller has changed from the initial value or not. If it didn't change, it'll show the text being returned in the if statement. When your user picks a date, you are change the value of it to the date picked, so it'll pass the validation, otherwise, it'll fail.

Upvotes: 1

Related Questions