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



我的目标是通过输入的生日来检查用户的年龄,如果用户不是18岁或18岁以上,则返回错误。但我不知道该怎么做。日期格式为"dd-MM-yyyy"。有什么办法吗?

为了方便地解析日期,我们需要包intl:

https://pub.dev/packages/intl#-安装选项卡-

因此,将此依赖项添加到您的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 || 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);
}

我提出的最好的年龄验证是基于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?23(?:(?:(?:1[6-9]|[2-9]d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1d|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

我希望你会觉得这很有用

您可以使用扩展来添加一个函数,该函数将检查DateTime。例如:

extension DateTimeX on DateTime {
bool isUnderage() =>
(DateTime(DateTime.now().year, this.month, this.day)
.isAfter(DateTime.now())
? DateTime.now().year - this.year - 1
: DateTime.now().year - this.year) < 18;
}
void main() {
final today = DateTime.now();
final seventeenY = DateTime(today.year - 18, today.month, today.day + 1);
final eighteenY = DateTime(today.year - 18, today.month, today.day);

print(today.isUnderage());
print(seventeenY.isUnderage());
print(eighteenY.isUnderage());
}

值得注意的是,这不需要intl或任何其他外部包。将此右粘贴到dartpad.dev中进行测试。

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

String _data = '16-04-2000';
DateTime _dateTime = DateTime(
int.parse(_data.substring(6)),
int.parse(_data.substring(3, 5)),
int.parse(_data.substring(0, 2)),
);
int yeardiff = DateTime.fromMillisecondsSinceEpoch(
DateTime.now().difference(_dateTime).inMilliseconds)
.year -
1970;
print(yeardiff);
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"),
);
}
}

如果您使用的是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")
)

18年中有6570天。所以我创建了一个简单的操作来检查输入的日期和今天的日期相比是否大于6570天。

DateTime.now().difference(date) < Duration(days: 6570)

如果这是真的,则用户小于18岁,如果不是,则用户大于18岁。也适用于白天。

这是我的if块:

if (DateTime.now().difference(date) < Duration(days: 6570)) {
EasyLoading.showError('You should be 18 years old to register');} 
else {
store.changeBirthday(date);}
import 'package:intl/intl.dart';
void main() {
print(_isAdult('12-19-2004') ? 'over 18' : 'under 18');
}
bool _isAdult(String dob) {
final dateOfBirth = DateFormat("MM-dd-yyyy").parse(dob);
final now = DateTime.now();
final eighteenYearsAgo = DateTime(
now.year - 18,
now.month,
now.day + 1, // add day to return true on birthday
);
return dateOfBirth.isBefore(eighteenYearsAgo);
}

类似于@Broken的公认答案,但我认为这更具可读性。

DartPad测试https://dartpad.dev/?id=53885d812c90230f2a5b786e75b6cd82

相关内容

  • 没有找到相关文章

最新更新