Search code examples
javascriptreactjsreact-final-form

React final form at least one mandatory field


I have the following:

export const isOneFieldValid = (val: string) => { 
  console.log(val)
  return val ? undefined : true
}

...
const validate = (field: string) => {
  switch (field) {
    case 'email': {
      return composeValidators(isOneFieldValid, isValidEmail, hasStringeMaxLength)
    }
    case 'workPhone':
    case 'homePhone':
    case 'mobile': {
      return composeValidators(isOneFieldValid, isNumber, hasNumberMaxLength)
    }
    default:
      return undefined
  }
}
...

This validates all of the 4 fields, but is there a way to validate only one field assuming that all of them are empty?

As long as there is one way to contact the user I can submit the form


Solution

  • sounds like you need a form level validation, not field level?

    <Form
        onSubmit={onSubmit}
        validate={values => {
                const errors = {}
                if (values.email && isValidEmail && hasStringMaxLength) {
                  return ;
                } else {
                 errors.email = 'Require';
                }
                if (writeFunctionToCheckWorkPhone) {
                  return;
                } else {
                  error.workPhone = 'Require';
                }
                if (writeFunctionToCheckHomePhone) {
                  return ;
                } else {
                  error.homePhone = 'Require';
                }
               if (writeFunctionToCheckMobile) {
                  return ;
                } else {
                  error.mobile = 'Require';
                }
                return errors;
              }}
        ...