Yup: How to make a conditional rule?

Asked

Viewed 241 times

1

I’m trying to make a conditional rule with Yup, but following the steps of the documentation, I get this mistake:

Typeerror: ref must be a string, got: true if (typeof key !== 'string') throw new Typeerror('ref must be a string, got: ' + key); | 17 | this.key = key.Trim(); 18 | if (key === ') throw new Typeerror('ref must be a non-empty string'); 19 | this.isContext = this.key[0] === prefixes.context;

That’s my definition of rules:

const schema = Yup.object().shape({
    login: Yup.string()
        .email('Email don't valid')
        .required('Fill the email!'),
    password: Yup.string().required('You need to fill the password').when(user.hasOwnProperty('id'), {
        is: false
    }),
})

I want to make a conditional rule that when my object user not own the property id, make the password required. Any idea?

  • Answer solved your problem? If yes, consider marking it as a solution

1 answer

1

Try this.

const schema = Yup.object().shape({
    login: Yup.string()
        .email('Email don"t valid')
        .required('Fill the email!'),
    password: Yup.string().when('userId', (user.hasOwnProperty('id'), field) =>
          user.hasOwnProperty('id') ? field.required() : field
    ),
})
  • I’ll test soon and give you feedback

Browser other questions tagged

You are not signed in. Login or sign up in order to post.