Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

javascript - How to create custom validation in a field that need value from another field using formik and yup

I use formik and yup to handle form validation in my app.

I have 2 field that related to each other, let's say field 'date' and field 'time'.

I want to make a custom validation in field 'time' to check whether the time of the day has passed or not based on value from field 'date'

For example, today is 26 Feb 2021 and 08.00 AM, so that users cannot choose a time below 8 o'clock.

date: string().required('date required'),
time: string()
  .required('time is require')
  .matches(myCustomRegex)
question from:https://stackoverflow.com/questions/65903090/how-to-create-custom-validation-in-a-field-that-need-value-from-another-field-us

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I solve it by using .when method.

date: string().required('date required'),
time: string()
  .required('time is require')
  .matches(myCustomRegex)
  .when('date', {
    .is: data => date && date moment(new Date(),'x').format('DD/MM/YYYY') === moment(new Date(date), 'x').format('DD/MM/YYYY')
    .then: String().test(
      'time',
      'Start Time must not  be less than the current time',
      value => {
        if(value){
          const currentHour = new Date().getHours();
          const currentMinute = new Date().getMinutes();
          const userPickHour = parseInt(value.split(':')[0], 10)
          const userPickMinute = parseInt(value.split(':')[1], 10);
          if(userPickHour < currentHour){
            return false;
          }else if(userPickHour === currentHour && userPickMinute <= currentMinute){
            return false;
          }else {
            return true;
          }
        }
        return true;
      }
    )
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...