Yup validation convert empty string to default value
Asked Answered
Q

2

5

In my Yup schema I was my String field name to allow you to pass in any string, an empty string, or nothing at all. If you pass in a string, it passes. If you pass in an empty string or nothing, I want to convert to a default value.

This is the schema that I thought would cover it:

const mySchema = yup.object().shape({
  name: yup.string('Name must be a string').max(100, 'Name has a max of 100 characters').default('John Doe')
});

However, if I pass in an empty string '', it does not trigger the default conversion and it just passed through as an empty string. I've tried adding required() but that just makes the line fail if I pass an empty string. I've tried nullable() and trim() but nothing seems to work.

How can I make the default value replace empty strings?

Quarterdeck answered 25/6, 2021 at 19:58 Comment(1)
I think you will need to handle that case in a transform as an empty string ('') is a string and would not trigger the default.Gerber
Q
10

I ended up adding a simple method to transform empty string to undefined which will get picked up in the default:

// Add method
yup.addMethod(yup.string, 'stripEmptyString', function () {
  return this.transform((value) => (value === '' ? undefined : value));
});

// Usage
const mySchema = yup.object().shape({
  name: yup.string('Name must be a string').stripEmptyString().default('John Doe')
});
Quarterdeck answered 28/6, 2021 at 13:27 Comment(0)
S
1

You can use this

const voidIfEmptyString = (value) => (value === '' ? undefined : value)

const mySchema = yup.object().shape({
  name: yup.string('Name must be a string')
    .transform(voidIfEmptyString)
    .max(100, 'Name has a max of 100 characters')
    .default('John Doe')
});
Saguenay answered 1/2 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.