programing

Yup에서의 조건부 검증

minimums 2023. 3. 14. 21:30
반응형

Yup에서의 조건부 검증

확인란이 선택되어 있는 경우에만 표시되는 이메일 필드가 있습니다(부울 값은true폼이 송신되었을 때, 체크 박스가 온이 되어 있는 경우(부울란은 true).

지금까지 제가 시도한 것은 다음과 같습니다.

const validationSchema = yup.object().shape({
   email: yup
         .string()
         .email()
         .label('Email')
         .when('showEmail', {
             is: true,
             then: yup.string().required('Must enter email address'),
         }),
    })

그 밖에도 몇 가지 변형을 시도했지만 Formik과 Yup에서 오류가 발생했습니다.

Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
    at yupToFormErrors (formik.es6.js:6198)
    at formik.es6.js:5933
    at <anonymous>
yupToFormErrors @ formik.es6.js:6198

그리고 Yup에게 인증 오류도 받습니다.내가 뭘 잘못하고 있지?

show Email 필드의 검증 규칙을 정의하지 않았을 수 있습니다.

테스트하기 위해 CodeSandox를 실행했는데, 바로 다음과 같이 추가했습니다.

showEmail: yup.boolean()

폼이 정상적으로 검증을 개시해, 에러는 발생하지 않았습니다.

다음 URL은 https://codesandbox.io/s/74z4px0k8q

그리고 미래에는 이것이 올바른 검증 스키마였습니다.

validationSchema={yup.object().shape({
    showEmail: yup.boolean(),
    email: yup
      .string()
      .email()
      .when("showEmail", {
        is: true,
        then: yup.string().required("Must enter email address")
      })
  })
}

여기 포믹 작가...

만들기 위해서Yup.when올바르게 동작하기 위해서는, 추가하셔야 합니다.showEmail로.initialValuesYup 스키마 모양에 맞춰주세요.

일반적으로 사용하는 경우validationSchemaYup이 즉시 볼 수 있도록 폼의 모든 필드에 초기값이 있는지 확인하는 것이 좋습니다.

결과는 다음과 같습니다.

<Formik 
  initialValues={{ email: '', showEmail: false }}
  validationSchema={Yup.object().shape({
    showEmail: Yup.boolean(),
    email: Yup
      .string()
      .email()
      .when("showEmail", {
        is: true,
        then: Yup.string().required("Must enter email address")
      })
  })
}

/>

@Joang Cunha의 답변에 전적으로 동의합니다.라디오 버튼의 사용 예에 대한 보충 자료입니다.

라디오 버튼을 조건으로 사용하면 부울 대신 문자열 값을 확인할 수 있습니다.is: 'Phone'

const ValidationSchema = Yup.object().shape({
  // This is the radio button.
  preferredContact: Yup.string()
    .required('Preferred contact is required.'),
  // This is the input field.
  contactPhone: Yup.string()
    .when('preferredContact', {
      is: 'Phone',
      then: Yup.string()
        .required('Phone number is required.'),
    }),
  // This is another input field.
  contactEmail: Yup.string()
    .when('preferredContact', {
      is: 'Email',
      then: Yup.string()
        .email('Please use a valid email address.')
        .required('Email address is required.'),
    }),

});

이 옵션 버튼은 ReactJS로 작성되어 있습니다.onChange 메서드는 상태 체크를 트리거하는 키입니다.

<label>
  <input
    name="preferredContact" type="radio" value="Email"
    checked={this.state.preferredContact == 'Email'}
    onChange={() => this.handleRadioButtonChange('Email', setFieldValue)}
  />
  Email
</label>
<label>
  <input
    name="preferredContact" type="radio" value="Phone"
    checked={this.state.preferredContact == 'Phone'}
    onChange={() => this.handleRadioButtonChange('Phone', setFieldValue)}
  />
  Phone
</label>

그리고 여기 라디오 버튼이 바뀌었을 때 콜백 기능이 있습니다.Formik을 사용하고 있다면 setFieldValue를 사용하는 것이 좋습니다.

handleRadioButtonChange(value, setFieldValue) {
  this.setState({'preferredContact': value});
  setFieldValue('preferredContact', value);
}

복잡한 경우에서도 기능을 사용할 수 있습니다.복잡한 검증에 도움이 되는 기능 케이스

validationSchema={yup.object().shape({
    showEmail: yup.boolean(),
    email: yup
      .string()
      .email()
      .when("showEmail", (showEmail, schema) => {
        if(showEmail)
          return schema.required("Must enter email address")
        return schema
      })
  })
}
email: Yup.string()
    .when(['showEmail', 'anotherField'], {
        is: (showEmail, anotherField) => {
            return (showEmail && anotherField);
        },
        then: Yup.string().required('Must enter email address')
    }),

그것은 나에게 매우 효과가 있다:

   Yup.object().shape({
    voyageStartDate:Yup.date(),
    voyageEndDate:Yup.date()
        .when(
            'voyageStartDate',
            (voyageStartDate, schema) => (moment(voyageStartDate).isValid() ? schema.min(voyageStartDate) : schema),
        ),
})

나는 vee-validate와 함께 yup을 사용한다.

vee-brought.

프로젝트 샘플 코드입니다.

const schema = yup.object({
    first_name: yup.string().required().max(45).label('Name'),
    last_name: yup.string().required().max(45).label('Last name'),
    email: yup.string().email().required().max(255).label('Email'),
    self_user: yup.boolean(),
    company_id: yup.number()
        .when('self_user', {
            is: false,
            then: yup.number().required()
        })
})
const { validate, resetForm } = useForm({
    validationSchema: schema,
    initialValues: {
        self_user: true
    }
})

const {
    value: self_user
} = useField('self_user')
const handleSelfUserChange = () => {
    self_user.value = !self_user.value
}

언급URL : https://stackoverflow.com/questions/49394391/conditional-validation-in-yup

반응형