Home > Software engineering >  Validate optional string with Yup?
Validate optional string with Yup?

Time:11-07

I'm trying to validate a string with Yup:

const schema = object({
  firstname: string().optional().nullable().notRequired().min(2),
});

The rules should be a string but can be null or empty, and if there is a value, then the length must be more than 2.

But for some reason, it's not working:

const shouldWorks = [
  { firstname: 'bla' },
  { firstname: '' }, <--- its failed here.. empty is okay (.notRequired)
  { firstname: null },
];

How do I change the schema to fit my rules?

stackblitz

import { object, string } from 'yup';
console.clear();

const shouldWorks = [
  { firstname: 'bla' },
  { firstname: '' },
  { firstname: null },
];

const shouldNotWork = [{ firstname: 'a' }];

const schema = object({
  firstname: string().optional().nullable().notRequired().min(2),
});

shouldWorks.forEach((obj, i) => {
  console.log(`test: ${i}`);
  schema.validateSync(obj);
});

shouldNotWork.forEach((obj, i) => {
  try {
    schema.validateSync(obj);
    console.log(`error test: ${i} failed`);
  } catch (e) {
    console.log(`error test: ${i} pass`);
  }
});

CodePudding user response:

You can use yup.lazy to lazily decide what validators to use based on the value:

const schema = object({
  firstname: lazy((value) =>
    value === ''
      ? string()
      : string().optional().nullable().notRequired().min(2)
  ),
});

Stackblitz

  • Related