Welcome Guest, Not a member yet? Register   Sign In
validation date of birth composed of 3 dropdowns: month, day, year
#1

(This post was last modified: 10-16-2021, 01:01 PM by Halim.)

I have form that contain: date of birth
date of birth is composed of 3 dropdowns:  month, day, year
I want validate the birthday to check if the user has a least 18 year old, and its valid date via custom rule like below, but it does not work,
Maybe I'm wrong, How to do something like that? Thanks


Code:
        $rules = [
            'first_name' => 'required|min_length[2]|max_length[20]',
            'last_name' => 'required|min_length[2]|max_length[20]',

            'month' => 'required',
            'day' => 'required',
            'year' => 'required',
            'birthday' => 'birthdayValidation[month,day,year]',
           
            'gender' => 'required|in_list[1,2]',
        ];
Reply
#2

(This post was last modified: 10-16-2021, 01:02 PM by Halim.)

I found solution by creating the custom rule below, and it seems working great, if anyone interested Smile


PHP Code:
<?php
namespace App\Validation;

class 
CustomRules{
    
    
/**
    * Rule is to validate birthday
    * @param string $str
    * @param string $fields
    * @param array $data
    * @param string $error
    * @return boolean
    */
    public function birthdayValidation(string $str nullstring $fields null, array $data = [], string &$error null) {
    
        
if(empty($data['month']) || empty($data['day']) || empty($data['year'])) {
            return true;
        }
        
        $birthDay 
$data['year'].'-'.$data['month'].'-'.$data['day'];
        
        
if(!checkdate($data['month'], $data['day'], $data['year'])) {
            $error "The Birthday field is not a valid date.";
            return false;
        }
        
        
if (time() < strtotime('+18 years'strtotime($birthDay))) {
            $error "You must be at least 18 years old.";
            return false;
        }
        
        
if (time() > strtotime('+99 years'strtotime($birthDay))) {
            $error "The age may not be greater than 99 years.";
            return false;
        }
        
        
return true;
    }
    

Reply
#3

(This post was last modified: 10-16-2021, 01:51 PM by includebeer.)

Thank you for posting your solution.
But what if my 102 years old grandpa wants to register on your website?  Tongue
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#4

(10-16-2021, 01:51 PM)includebeer Wrote: Thank you for posting your solution.
But what if my 102 years old grandpa wants to register on your website?  Tongue

You welcome, I thought maybe 99 is a max, I think fb do the same, not sure Smile
Reply




Theme © iAndrew 2016 - Forum software by © MyBB