Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to skip validation when value is empty? #2012

Open
stefanoinf opened this issue May 26, 2023 · 1 comment
Open

How to skip validation when value is empty? #2012

stefanoinf opened this issue May 26, 2023 · 1 comment

Comments

@stefanoinf
Copy link

Hi, I have a form with many optional fields. I would like to validate these optional fields only when they are not empty. I tried something like this:

yup.object({
    field1: yup.string().matches(/^([0-9]{10})$/, "Field 1 is not valid"),
    field2: yup.string().min(5, "Field 2 is not valid")
});

These 2 fields are not required (there isn't "required" validation), but even if they are empty Yup tries to validate them anyway so it gives error because the empty string doesn't match with that regex (field1) and the empty string is less than 5 (field2).

How to validate them only when they are not empty? I tried to add the .notRequired() method, but it still doesn't work.

I know there might be these solutions:

  1. Use the transform method and change the empty string in null then call the "nullable" method, like this:
field1: yup.string().matches(/^([0-9]{10})$/, "Field 1 is not valid").nullable().transform((value) => !!value ? value : null)

The issues with this solution are: this will also change the data value in the onSubmit function, the values will be null instead of empty strings but the API wants empty strings and not null values. The other problem (minor) is that I have many fields, so repeat that for every field is not elegant in my opinion.

  1. Use the when method and put the validation in the then when the value is not empty, like this:
field2: yup.string().when({
    is: (val) => val.length > 0,
    then: yup.string().min(5, "Field 2 is not valid")
})

this solution works without issues, it doesn't change the value to null like transform, but as I said, I have many optional fields and I would like to avoid to repeat that for every field .

Is there a better way to do that? If the answer is no, then probably I will use the solution 2.

I'm using version 1.2.0

@websitevirtuoso
Copy link

I have the same problem. even via transform I can't return null instead ""

start_publish_at: string()
.notRequired()
.transform((value, input) => (input === '' ? null : value))
.label(i18n.global.t('messages.start_publish_at')),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants