fatetefox
fatetefox

Reputation: 41

Is it possible to perform more validation after validationSchema, Yup, is passed?

Currently, I am doing some validation such as min length, max length, required and so on using Yup in combination. I wonder if i could perform some more validation which need request and response from server side after Yup validation is passed?

For example, i need a valid phone number format to be input first and after validate is passed, then I want to request to my backend to check if this phone number is existed. In case if it is already existed, then just set errors.phone: "Phone number is already registered." and show it inside ui using {touched.phone && errors.phone && <p>{errors.phone}</p>}. Please help shine me some light. I could not find any solutions for this.

Upvotes: 4

Views: 4261

Answers (2)

Vencovsky
Vencovsky

Reputation: 31683

You can use .test

As you can see in the docs example

let asyncJimmySchema = string().test(
  'is-jimmy',
  '${path} is not Jimmy',
  async (value) => (await fetch('/is-jimmy/' + value)).responseText === 'true',
});

The third paramether can be an async function and there you will make a call to your backend.

Edit:

If you want to validate only onBlur you can change Formik Prop validateOnBlur and validateOnChange.
The default value of both are true but if you set validateOnChange to false, it will only run validations onBlur. Notice that this will happen to all fields.

If you only that to happen only to one field, you will need to use field's validate prop and pass a function that receives the touched of the field to check it before calling the async function.

Upvotes: 2

Fraction
Fraction

Reputation: 12984

Try using string.test():

phone: Yup.string()
        .matches(/phone-number-regex/, 'Invalide phone number')
        .test(
          'phone',
          'Phone number is already registered',
           async (value) => (await fetch(`/validate-phone/${value}`)).responseText === 'true',
        ),
...

Demo: https://runkit.com/fraction01/yup-async-test

Upvotes: 2

Related Questions