custom validation in react native forms

50 Views Asked by At

I am validating the birthdate using pattern and message on birth-date input but now I wanna put another validation that age should be more than 16 years. I have written a custom function but its not working

validation={{
            pattern: /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/(19\d\d|20\d\d)$/,
            message: "Please enter a valid date in the format dd/mm/yyyy",
            custom: (value) => {
              console.log('Error in date')
              const dateParts = value.split('/');
              const day = parseInt(dateParts[0], 10);
              const month = parseInt(dateParts[1], 10);
              const year = parseInt(dateParts[2], 10);
          
              // Calculate the minimum birthdate for someone who is 16 years old
              const minBirthdate = new Date();
              minBirthdate.setFullYear(minBirthdate.getFullYear() - 16);
          
              // Create a Date object from the entered date
              const enteredDate = new Date(year, month - 1, day); // Month is 0-based
               console.log('Error in date')
              if (enteredDate >= minBirthdate) {
                return { type: "age" };
              }
          
              return undefined; // Validation passed
            }
          }}
1

There are 1 best solutions below

0
Shahjahan On

You may calculate the age like so

const getAgeInYears = (enteredDate) => new Date().getFullYear() - new Date(enteredDate).getFullYear();

const age = getAgeInYears('2008-09-12') // Change target date here
console.log(age < 16 ? 'Under age' : 'Good to go')