如何在颤振中进行年龄验证

时间:2020-04-16 12:03:57

标签: date validation flutter dart

我的目标是按照输入的生日检查用户的年龄,如果用户不超过18岁,则返回错误。但是我不知道该怎么做。日期格式为“ dd-MM-yyyy”。任何想法如何做到这一点?

6 个答案:

答案 0 :(得分:3)

我曾经想过的最佳年龄验证是基于Regex。
以下逻辑涵盖了所有与断点相关的年龄。

// regex for validation of date format : dd.mm.yyyy, dd/mm/yyyy, dd-mm-yyyy
RegExp regExp = new RegExp(
    r"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$",
    caseSensitive: true,
    multiLine: false,
  );

//method to calculate age on Today (in years)
  int ageCalculate(String input){
  if(regExp.hasMatch(input)){
  DateTime _dateTime = DateTime(
      int.parse(input.substring(6)),
      int.parse(input.substring(3, 5)),
      int.parse(input.substring(0, 2)),
    );
    return DateTime.fromMillisecondsSinceEpoch(
                DateTime.now().difference(_dateTime).inMilliseconds)
            .year -
        1970;
  } else{
    return -1;
  }
}

void main() {
// input values and validations examples
  var input = "29.02.2008";
  print("12.13.2029 : " + regExp.hasMatch("12.13.2029").toString());
  print("29.02.2028 : " + regExp.hasMatch("29.02.2028").toString());
  print("29.02.2029 : " + regExp.hasMatch("29.02.2029").toString());
  print("11/12-2019 : " + regExp.hasMatch("11/12-2019").toString());
  print("23/12/2029 : " + regExp.hasMatch("23/12/2029").toString());
  print("23/12/2029 : " + regExp.hasMatch(input).toString());
  print("sdssh : " + regExp.stringMatch("sdssh").toString());   
  print("age as per 29.02.2008 : " + ageCalculate(input).toString());
}

输出

 12.13.2029 : false
 29.02.2028 : true
 29.02.2029 : false
 11/12-2019 : false
 23/12/2029 : true
 23/12/2029 : true
 sdssh : null
 age as per 29.02.2008 : 12

希望您会发现这很有用。 :)

答案 1 :(得分:1)

包裹

要轻松解析日期,我们需要打包intl

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

因此将此依赖项添加到您的pubspec.yaml文件(和get新的依赖项)中

解决方案#1

您可以简单比较年份:

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 && dayDiff >= 0;
}

但这并不总是正确的,因为到今年年底您还不是成年人。

解决方案2

因此,更好的解决方案是将出生日提前18天并与当前日期进行比较。

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);
}

答案 2 :(得分:0)

您可以通过以下方式找到年份差异。

selected

答案 3 :(得分:0)

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';     

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),      
    );
  }
}

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

  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String dateFormate;
  @override
  Widget build(BuildContext context) {
     var dateNow = new DateTime.now();
     var givenDate = "1969-07-20";
     var givenDateFormat = DateTime.parse(givenDate);
     var diff = dateNow.difference(givenDateFormat);
     var year = ((diff.inDays)/365).round();

    return Container(
      child: (year < 18)?Text('You are under 18'):Text("$year years old"),
    );
  }
}

答案 4 :(得分:0)

一线踢。假设您已经在使用DateTime:

bool _isUnderage() => (DateTime(DateTime.now().year, this.birthday.month, this.birthday.day).isAfter(DateTime.now()) ? DateTime.now().year - this.birthday.year - 1 : DateTime.now().year - this.birthday.year) < 18;

答案 5 :(得分:0)

如果您使用的是 intl 包,这很简单。确保您为日期选择器和验证年龄的函数设置了相同的格式。

您可以使用以下代码来计算今天的日期和输入的日期之间的差异:

double isAdult(String enteredAge) {
    var birthDate = DateFormat('MMMM d, yyyy').parse(enteredAge);
    print("set state: $birthDate");
    var today = DateTime.now();

    final difference = today.difference(birthDate).inDays;
    print(difference);
    final year = difference / 365;
    print(year);
    return year;
  }

您可以为函数的返回值创建一个条件,例如:

Container(
  child: (isAdult(selecteddate) < 18 ? Text("You are under age") : Text("$selecteddate is your current age")
)