React+Formik+Yup - validate in order

Joined
Dec 2, 2022
Messages
7
Reaction score
1
Hi!
I use Formik+Yup for my forms. I have this validation scheme that checks the domain entered by the user for correctness, and also by sending this domain to the API to check if it is on cloudflare:

JavaScript:
const validationSchema = Yup.object().shape({
    domainName: Yup.string()
      .required('The website URL is required')
      .matches(URL_REGEX, 'Enter correct URL')
      .test('is-on-cloudflare', 'Invalid domain name', async (domainName: string) => {
        const re = /^https?:\/\//
        if (re.test(domainName)) {
          const res = await checkCloudflareStatus(domainName)
          if (res.data?.on_cloudflare) {
            return true
          }
        }
        return false
      }),
  })

How can I trigger a domain verification request in API only after it has passed other validations, but not in parallel?
 
Joined
Dec 2, 2022
Messages
7
Reaction score
1
Found this solution:

JavaScript:
const firstValidation = Yup.string()
    .required('The website URL is required')
    .matches(URL_REGEX, 'Enter correct URL')
  const validationSchema = Yup.object().shape({
    domainName: firstValidation
      .test('is-on-cloudflare', 'Invalid domain name', async (domainName: string) => {
        if (await firstValidation.isValid(domainName)) {
          const res = await checkCloudflareStatus(domainName)
          return Boolean(res.data?.on_cloudflare)
        }
        return true
      }),
  })
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,888
Messages
2,569,964
Members
46,294
Latest member
HollieYork

Latest Threads

Top