programing

Formik, Yup 및 React를 사용한 비동기 검증

linuxpc 2023. 3. 27. 21:04
반응형

Formik, Yup 및 React를 사용한 비동기 검증

Formik으로 비동기 검증을 하고 yup으로 검증을 하고 싶은데 예제나 데모를 찾을 수 없습니다.

const validationSchema = Yup.object().shape({
    username:
        Yup.string()
            .test('checkDuplUsername', 'same name exists', function (value) {
                return new Promise((resolve, reject) => {
                    kn.http({
                        url: `/v1/users/${value}`,
                        method: 'head',
                    }).then(() => {
                        // exists
                        resolve(false)
                    }).catch(() => {
                        // note exists
                        resolve(true)
                    })
                })
            })
})

테스트 방법을 통해 비동기 처리를 제공합니다.
(kn은 나의 아약스 약속 함수)
좋은 하루 되세요.

사실 조금 더 간단하게 할 수 있어요.


const validationSchema = Yup.object().shape({
    username: Yup.string().test('checkEmailUnique', 'This email is already registered.', value =>
        fetch(`is-email-unique/${email}`).then(async res => {
            const { isEmailUnique } = await res.json()

            return isEmailUnique
        }),
    ),
})

예를 들어 가짜 약속을 사용하는 경우 다음과 같이 할 수 있습니다.

  const Schema = yup.object().shape({
      password: yup
   .string()
  .test("validPassword","Password requires one special character",
  function (value) {
    return new Promise((resolve) => {
      setTimeout(() => {
        if (
          /^[0-9A-Za-z]*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?][0-9a-zA-Z]*$/.test(
            value
          )
        ) {
          resolve(true);
        } else {
          resolve(false);
        }
      }, 100);
    });
  }
 ),
});
    

사용할 수 있습니다.async/await와 함께yup커스텀 검증기

let field = yup.string().test(
'test-id',
'error message in case of fail',
 async function validateValue(value){
  try{
    
     // validation logic
     return false; // or true as you see fit

  } catch(error){

  }
});

돌아가다true당신이 받아들이는 가치들에 대해서

돌아가다false거부한 값에 대해

항상 부울을 반환하거나,finally자신을 보증하지 않으면 차단합니다.

API 콜과 비동기화하는 방법은 다음과 같습니다.

const validationSchema = Yup.object().shape({
  username: Yup.string().test('checkDuplUsername', 'same name exists', function (value) {
    if (!value) {
      const isDuplicateExists = await checkDuplicate(value);
      console.log("isDuplicateExists = ", isDuplicateExists);
      return !isDuplicateExists;
    }
    // WHEN THE VALUE IS EMPTY RETURN `true` by default
    return true;
  }),
});

function checkDuplicate(valueToCheck) {
  return new Promise(async (resolve, reject) => {
    let isDuplicateExists;

    // EXECUTE THE API CALL TO CHECK FOR DUPLICATE VALUE
    api.post('url', valueToCheck)
    .then((valueFromAPIResponse) => {
      isDuplicateExists = valueFromAPIResponse; // boolean: true or false
      resolve(isDuplicateExists);
    })
    .catch(() => {
      isDuplicateExists = false;
      resolve(isDuplicateExists);
    })
  });
}

언급URL : https://stackoverflow.com/questions/55811114/async-validation-with-formik-yup-and-react

반응형