Get Formik Validation Current Year and Up

Viewed 2501

I need to get the validation using Formik that input should only be currentYear and up.

 const currentYear = new Date().getFullYear();

expiryYear: yup
.string()
.required('Select expiry year')
.min(4, `Invalid year format (Example: ${currentYear + 4})`)
.max(4, `Invalid year format (Example: ${currentYear + 4})`)
.when('startDate', (currentYear, schema) => currentYear && schema.min(currentYear)),
2 Answers

Try this please:

yup.date()
 .min(new Date().getFullYear(),
 'Year must be current year or greater than current year');

Check the demo

If you would like to validate the year's length, you can use this:

yup.number()
.test('len', 'Must be exactly 4 characters', 
val => val && val.toString().length === 4 ).min(new Date().getFullYear());

This will validate the length of the year first, then check whether it is greater than or equal to current year.

this is how I did it:

import yup from 'yup';

// useState Declaration and Definition area

  const [year, setYear]= React.useState('');
let [yearError, setYearError]= React.useState(false)
 
//Validating year for being a number, not null and not beyong current year

  const YearValidator= yup.number().test(val => val !== '' && val.toString().length 
  === 4 ).max(new Date().getFullYear()).required();

//now passing here year value (entered by user) for validation

   const validYear = YearValidator.isValidSync(year);

//showing error if validYear is not true..

yearError = validYear ? " year submitted" : "year is not valid";
    console.log(yearError);
    setYearError(yearError); 

Now create a handleYearChange() function that takes the event change as argument like this...

const handleYearChange = (event)=>{
    setYear(event.target.value);
  }

Now call this function from your HTML tag where user enters the YEAR value

<div>
   <p className=""> Year of PassOut* </p>
      <input type="number" onChange={handlePassoutYearChange}/>
       <span> {yearError}</span>
  </div>
Related