Home > Net >  Validate date of birth in Flutter
Validate date of birth in Flutter

Time:06-12

I've created a form using Flutter which has date picker.enter image description here

User is supposed to pick his/her date of birth using it to make sure if the user is 16 and above. How do I validate date of birth to age 16?

Here are the parts of the code:

class _WelcomeScreenState extends State<WelcomeScreen> {
  TextEditingController dateinput = TextEditingController();
  final formKey = GlobalKey<FormState>();
  String name = "";

  @override
  void initState() {
    dateinput.text = ""; //set the initial value of text field
    super.initState();
  }

--

GestureDetector(
                child: TextField(
                  style: TextStyle(color: Colors.white),
                  controller:
                      dateinput, //editing controller of this TextField
                  decoration: InputDecoration(
                      labelStyle: TextStyle(color: Colors.white),
                      icon: Icon(Icons.calendar_today),
                      iconColor: Colors.white, //icon of text field
                      labelText: "Enter Date Of Birth" //label text of field
                      ),
                  readOnly:
                      true, //set it true, so that user will not able to edit text
                  onTap: () async {
                    DateTime? pickedDate = await showDatePicker(
                        context: context,
                        initialDate: DateTime.now(),
                        firstDate: DateTime(
                            1900), //DateTime.now() - not to allow to choose before today.
                        lastDate: DateTime(2040));

                    if (pickedDate != null) {
                      print(
                          pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                      String formattedDate =
                          DateFormat('dd-MM-yyyy').format(pickedDate);
                      print(
                          formattedDate); //formatted date output using intl package =>  2021-03-16
                      //you can implement different kind of Date Format here according to your requirement

                  setState(() {
                    dateinput.text =
                        formattedDate; //set output date to TextField value.
                  });
                } else {
                  print("Date is not selected");
                }
              },
            ),
          ),

CodePudding user response:

A naive approach would be to just construct a DateTime object from the selected birth date and to then compute DateTime.now().difference(birthDate).inDays / 365. That doesn't account for leap days, and maybe it's close enough, but it's not how a human would compute age.

When attempting to solve a programming problem, one of the first things you usually should ask yourself is: How would you solve this without a computer?

To determine if someone is at least 16 years old, you would take the current date, subtract 16 from the year, use the same month and day1, and see if their birthday is on or before that date, ignoring the time. So just do that:

extension IsAtLeastYearsOld on DateTime {
  bool isAtLeastYearsOld(int years) {
    var now = DateTime.now();
    var boundaryDate = DateTime(now.year - years, now.month, now.day);

    // Discard the time from [this].
    var thisDate = DateTime(year, month, day);

    // Did [thisDate] occur on or before [boundaryDate]?
    return thisDate.compareTo(boundaryDate) <= 0;
  }
}

void main() {
  // The results below were obtained with 2022-06-11 as the current date.
  print(DateTime(2006, 6, 10).isAtLeastYearsOld(16)); // Prints: true
  print(DateTime(2006, 6, 11).isAtLeastYearsOld(16)); // Prints: true
  print(DateTime(2006, 6, 12).isAtLeastYearsOld(16)); // Prints: false
}

1 This should be fine even if the current date is a leap day since DateTime will convert February 29 into March 1 for non-leap years.

CodePudding user response:

With a function for calculate :

int calculateAge(DateTime birthDate) {
  DateTime currentDate = DateTime.now();
  int age = currentDate.year - birthDate.year;
  if (birthDate.month > currentDate.month) {
    age--;
  } else if (currentDate.month == birthDate.month) {
    if (birthDate.day > currentDate.day) {
      age--;
    }
  }
  return age;
}
  • Related