DEV Community

Krzysztof Żuraw
Krzysztof Żuraw

Posted on • Originally published at krzysztofzuraw.com on

3 1

Yup validation - one field required but not both at the same time

Recently I was working with yup for form validation andI faced the following problem:

I have two fields inside my form. I want the user to provide one of them but not both at the same time. I’ve played a little bit with different ideas to get solution below. It is using test and when functions from yup:

import { object, string } from 'yup';

const schema = object().shape(
  {
    userName: string()
      .test(
        'notBothAtTheSameTime', // test name
        'You cannot pass user name at the same time as user email', // validation message to the user
        // it has to be function definition to use `this`
        function(userName) {
          const { userEmail } = this.parent;
          if (userEmail && userName) {
            return false; // when user enters both userEmail & userName do not validate form
          }
          return true;
        }
      )
      .when(['userEmail'], {
        is: userEmail => !userEmail,
        then: string().required('User name is required'),
      }),
    userEmail: string()
      .test(
        'notBothAtTheSameTime',
        'You cannot pass user email at the same time as user name',
        function(userEmail) {
          const { userName } = this.parent;
          if (userName && userEmail) {
            return false;
          }
          return true;
        }
      )
      .when(['userName'], {
        is: userName => !userName,
        then: string().required('User email is required'),
     email
  [['userName', 'userEmail']] // important to add
);
Enter fullscreen mode Exit fullscreen mode

If you want you can extract it to its own function via addMethod.

That’s all 🎉. Now user should get and error when they provide both userName & userEmail.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

Collapse
 
temurbekruziev profile image
Temurbek Ruziev

ssssssssssssssssss

sssssssssssss

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series