Search code examples
datevalidationflutterdart

How to make age validation in flutter


My goal is to check users age by entered birthday and return error if user is not 18 years old or older. But i have no idea how to do that. Date format is "dd-MM-yyyy". Any ideas how to do that?


Solution

  • Package

    To easily parse date we need package intl:

    https://pub.dev/packages/intl#-installing-tab-

    So add this dependency to youd pubspec.yaml file (and get new dependencies)

    Solution #1

    You can just simple compare years:

    bool isAdult(String birthDateString) {
      String datePattern = "dd-MM-yyyy";
    
      DateTime birthDate = DateFormat(datePattern).parse(birthDateString);
      DateTime today = DateTime.now();
    
      int yearDiff = today.year - birthDate.year;
      int monthDiff = today.month - birthDate.month;
      int dayDiff = today.day - birthDate.day;
    
      return yearDiff > 18 || yearDiff == 18 && monthDiff > 0 || yearDiff == 18 && monthDiff == 0 && dayDiff >= 0; 
    }
    

    But it's not always true, because to the end of current year you are "not adult".

    Solution #2

    So better solution is move birth day 18 ahead and compare with current date.

    bool isAdult2(String birthDateString) {
      String datePattern = "dd-MM-yyyy";
    
      // Current time - at this moment
      DateTime today = DateTime.now();
    
      // Parsed date to check
      DateTime birthDate = DateFormat(datePattern).parse(birthDateString);
    
      // Date to check but moved 18 years ahead
      DateTime adultDate = DateTime(
        birthDate.year + 18,
        birthDate.month,
        birthDate.day,
      );
    
      return adultDate.isBefore(today);
    }