0
votes

I have a wizard form where I need to check if there is any validation issue on each step so that if there is an issue then don't allow user to go to next step unless there is no validation error. On this check, I am facing an issue. The issue is, on step 1 I have following fields

Email
Company
Address
Contact number 1
Contact number 2

where first four fields are required and last i.e Contact number 2 is optional but if user inputs value to contact number 2 then a validation has to be checked.

In my case, even if user does not provide any value to Contact number 2, the error object will have its field because of which user cannot go to next step.

  company: Yup.string().max(250).required(),
  email: Yup.string().email().trim().max(100).required(),
  address: Yup.string().min(5).max(60).required(),
  contactNo1: Yup.string()
    .matches(phoneRegex, 'Phone number is not valid')
    .required('Phone number is not valid'),
  contactNo2: Yup.string()
    .notRequired()
    .test('contact_no_2', 'Contact no 2 check', function (value) {
      if (!!value) {
        const schema = Yup.string().matches(
          /(^$|^(\+?)[1-9]{1}([0-9]){8,12}$)/,
          'Phone number is not valid',
        )
        return schema.isValidSync(value)
      }
      return true
    }),

How do i allow user to go to next step only if those required fields do not have any validation issue and if either there is no any value for contactNo2 or if there is a value with a valid phone number?

for checking the disabled state what i have done is

const {
    company,
    email,
    address,
    contactNo1,
    gender,
  } = props.values
  const disabled =
    !(company && email && address && contactNo1) &&
    !(
      props.errors['company'] &&
      props.errors['email'] &&
      props.errors['address'] &&
      props.errors['contactNo1'] &&
      props.errors['contactNo2']
    )

<Button>
    <Button.Content
    type="button"
    disabled={disabled}
    onClick={props.navigateNext}
    >
    Next
    </Button.Content>
</Button>

In short, how do i allow to next step if there is no validation issue on required fields and on optional field if and if value is provided?

1

1 Answers

0
votes

On my project I do:

handleNext = (activeStep, validateForm) => {
 validateForm().then((errors) => {
  setFieldTouched("company", true);
  setFieldTouched("email", true);
  setFieldTouched("address", true);
  setFieldTouched("contactNo1", true);
  setFieldTouched("contactNo2", true);
  if (!getIn(errors, "company") || !getIn(errors, "email") || !getIn(errors, "address") || !getIn(errors, "contactNo1") || !getIn(errors, "contactNo2")) {
     this.setState((prevState) => ({
        activeStep: prevState.activeStep + 1,
     }));
    }
 }
};
...
<Button>
    <Button.Content
    type="button"
    disabled={disabled}
    onClick={() => props.navigateNext(activeStep, validateForm)}
    >
    Next
    </Button.Content>
</Button>

activeStep I save on State. And this work for me