How to get yup.string() to require string of any length (including 0)

Viewed 9291

I'm wondering if someone could advise me on how to get yup to validate strings of any length (including length 0).

Just using

yup.string().required().validateSync("")

will throw an error on an empty string...

In the past this was the recommended way to do it:

string().required().min(0) 

but that way no longer works.. (https://github.com/jquense/yup/issues/136#issuecomment-339235070)

Can someone advise me on how to get yup to require that a string is sent, but to not error on length 0 strings?

Thanks!

4 Answers

What I would suggest would be to drop the .required() and, instead, look at using typeError for your validation whilst enabling strict to stop non-string values being coerced and transformed.

This will enable you to allow string values of any length whilst still erroring on values which are not strings.

Example:

yup.string().typeError().strict(true).validateSync(1) // Error
yup.string().typeError().strict(true).validateSync(null) // Error
yup.string().typeError().strict(true).validateSync({}) // Error
yup.string().typeError().strict(true).validateSync("") // Valid
yup.string().typeError().strict(true).validateSync("Foo") // Valid

typeError also has an optional message parameter allowing you to provide the error message there and then if you don't wish to handle it again later.

I like using mixed , test and typeof === 'string':

    firstName: Yup.mixed().test(
        'my test',
        'error: name is not a string',
        (text) => {
            if (typeof text === 'string') {
                return true
            } else {
                return false
            }
        }
    )
Required String that can be Empty

Example Field called: relevance_factor that has the same requirements as yours

let relevance_factor = yup
    .string()
    .test(
        'string-can-be-empty',
        MESSAGES.RELEVANCE_FACTOR_REQUIRED,
        function stringCanBeEmpty(value: any) {
            if (typeof value == 'string')
                return true;

            return false;
        }
    )
yup.string().defined().strict(true);

This will work for undefined values as well.

Related