Yup: Validate an input that can takes in multiple values e.g email or phone

Created on 10 Jan 2020  路  4Comments  路  Source: jquense/yup

Hi, is there any way that i can validate an input that can takes in multiple values e.g email or phone?

Example:
I have a login form that have two inputs, 1st input can takes in email or phone, 2nd input takes in password

Can i create a schema using Yup existing feature? can you guys provide an example?

Thanks a lot. Cheers.

Most helpful comment

@Cartrek-US This doesn't solve the issue. Here, we have a unique field which can be either an email or a phone. Is there a way to validate it with _Yup_, like alternatives method in _Joi_?

All 4 comments

You will first need to store the value of the two inputs into a single object.
something like
state = { email: "[email protected]", phone: "999-999-9999"}

Then you can write a schema like this
yup.object().shape( { email: yup.string()...., phone: yup.string()..... }

@Cartrek-US This doesn't solve the issue. Here, we have a unique field which can be either an email or a phone. Is there a way to validate it with _Yup_, like alternatives method in _Joi_?

@Cartrek-US This doesn't solve the issue. Here, we have a unique field which can be either an email or a phone. Is there a way to validate it with _Yup_, like alternatives method in _Joi_?

That's exactly the feature I'm missing in "yup" ...

Currently I'm using it at the backend with expressJS to validate queries in the request object, where a field might be of type 'string' or an 'object' with some properties.

Earlier with Joi I would use :

const Schema = Joi.object().keys( {
profile: Joi.alternatives().try(Joi.string(), { //some properties });
} )

I created example with or validate. Can you test?

https://codesandbox.io/s/example-with-or-validate-for-yup-nodelete-dgm4l

yup.addMethod(yup.string, "or", function(schemas, msg) {
  return this.test({
    name: "or",
    message: "Please enter valid url or email." || msg,
    test: value => {
      if (Array.isArray(schemas) && schemas.length > 1) {
        const resee = schemas.map(schema => schema.isValidSync(value));
        return resee.some(res => res);
      } else {
        throw new TypeError("Schemas is not correct array schema");
      }
    },
    exclusive: false
  });
});
Was this page helpful?
0 / 5 - 0 ratings