Validating Age Not Under 18

Age 18+ Validation with Ionic & Angular issue

The BEST way is to use Moment.js like:

npm install moment --save  

and

import * as moment from 'moment';

...

age18Check(birthday: Date) {
return moment(birthday).add(18, 'years') <= moment();
}

In this way you can also check the hour if you insert it in the birthday(Date). But if you have problems with hours you can also this:

age18Check(birthday: Date) {
return
moment(birthday).add(18, 'years').format('DD/MM/YYYY') <=
moment().format('DD/MM/YYYY');
}

I hope you was looking for this!

How to validate date of birth that should be less than 18 years old in Codeigneter

Alternatively, you could use a callback for this. Example:

public function your_form_page()
{
$this->load->library('form_validation');
// this part is when you set your validation rules
$this->form_validation->set_rules('DOM', 'Date of Birth', 'trim|required||callback_validate_age');
$this->form_validation->set_message('validate_age','Member is not valid!');
}

// you need to add this on the controller, this will be the custom validation
public function validate_age($age) {
$dob = new DateTime($age);
$now = new DateTime();
return ($now->diff($dob)->y > 18) ? false : true;
}

How to make age validation in flutter

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

How can I validate that someone is over 18 from their date of birth?

I think a better alternative would be to calculate the age of the user, and use that in your if statement.

See this SO answer on how to do just that:

Calculate age in JavaScript



Related Topics



Leave a reply



Submit