Home > Blockchain >  start date and end date validation in Flutter
start date and end date validation in Flutter

Time:06-10

In the below code I need to put validation like if the startdate is null give error to user or display the date chosen. I'm not sure how to do it.

String _displayText(String begin, DateTime? date) {
  if (date != null) {
    return '$begin Date: ${date.toString().split(' ')[0]}';
  } else {
    return 'Choose The Date';
  }
}

In the below it will display the date

Text(
  _displayText('Start', startdate),
  style: const TextStyle(
      fontWeight: FontWeight.bold, fontSize: 15, color: Colors.black),
),

CodePudding user response:

initialValue: "like this init"

CodePudding user response:

To validate the date, we are checking the date and controlling validator using date not text. Like

  String? endDateValidator(value) {
    if (startDate != null && endData == null) {
      return "select Both data";
    }
    if (endData == null) return "select the date";
    if (endData!.isBefore(startDate!)) {
      return "End date must be after startDate";
    }

    return null; // optional while already return type is null
  }

Inside the form TextFormFiled will be

TextFormField(
  controller: endDateController,
  readOnly: true,
  decoration: const InputDecoration(
    hintText: 'Choose The Date',
  ),
  onTap: () async {
    endData = await pickDate();
    endDateController.text = _displayText("start", endData);
    setState(() {});
  },
  validator: endDateValidator,
),

Test on DartPad.

Widget to play

class DateValidationInForm extends StatefulWidget {
    DateValidationInForm({Key? key}) : super(key: key);

  @override
  State<DateValidationInForm> createState() => _DateValidationInFormState();
}

class _DateValidationInFormState extends State<DateValidationInForm> {
  /// more about validation https://docs.flutter.dev/cookbook/forms/validation
  final _formKey = GlobalKey<FormState>();

  String _displayText(String begin, DateTime? date) {
    if (date != null) {
      return '$begin Date: ${date.toString().split(' ')[0]}';
    } else {
      return 'Choose The Date';
    }
  }

  final TextEditingController startDateController = TextEditingController(),
      endDateController = TextEditingController();

  DateTime? startDate, endData;

  Future<DateTime?> pickDate() async {
    return await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(1999),
      lastDate: DateTime(2999),
    );
  }

  String? startDateValidator(value) {
    if (startDate == null) return "select the date";
  }

  String? endDateValidator(value) {
    if (startDate != null && endData == null) {
      return "select Both data";
    }
    if (endData == null) return "select the date";
    if (endData!.isBefore(startDate!)) {
      return "End date must be after startDate";
    }

    return null; // optional while already return type is null
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          TextFormField(
            controller: startDateController,
            decoration: const InputDecoration(
              hintText: 'Choose The Date',
            ),
            onTap: () async {
              startDate = await pickDate();
              startDateController.text = _displayText("start", startDate);
              setState(() {});
            },
            readOnly: true,
            validator: startDateValidator,
            style: const TextStyle(
                fontWeight: FontWeight.bold, fontSize: 15, color: Colors.black),
          ),
          TextFormField(
            controller: endDateController,
            readOnly: true,
            decoration: const InputDecoration(
              hintText: 'Choose The Date',
            ),
            onTap: () async {
              endData = await pickDate();
              endDateController.text = _displayText("start", endData);
              setState(() {});
            },
            validator: endDateValidator,
            style: const TextStyle(
                fontWeight: FontWeight.bold, fontSize: 15, color: Colors.black),
          ),
          ElevatedButton(
            onPressed: () {
              _formKey.currentState?.validate();
            },
            child: Text("submit"),
          )
        ],
      ),
    );
  }
}

Check cookbook/forms/validation to learn more.

  • Related