Yup Mixed does not work notRequired or nullable

Asked

Viewed 63 times

4

Good afternoon, I am validating the data of a form with Yup and need that only images can be loaded, so I used the following code:

// formato que pode ser upado no input de email
const formatosSuportados = [
    "image/jpg",
    "image/jpeg",
    "image/gif",
    "image/png"
];    

// Validação das entradas
const EsquemaDeValidacao = Yup.object().shape({
    email: Yup.string().email().required('enter email'),
    corpo: Yup.string().max(500, "Too Long!").required('enter any message'),
    arquivo: Yup.mixed().nullable().test('fileFormat', 'Unsupported Format', arquivo => 
        arquivo && formatosSuportados.includes(arquivo.type)
    )
})  

The problem is that the file is mandatory for me to be able to send the email. It does not trigger any error, only it does not send if it has no file uploaded.

I’ve tried with nullable and notRequired, there’s some other way to do it?

1 answer

2


That expression will always come falso if it contains no selected file, then, I believe a very basic logic would be to test if the file does not exist, returns true, if it exists return the other test, example:

arquivo => { 
    if (!arquivo) { 
        return true;
    }
    return formatosSuportados.includes(arquivo.type) 
} 

this will solve your problem.

  • 1

    It worked, thank you!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.