Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple validation on one field Yup

Tags:

reactjs

yup

I'm validating a field by using YUP as validator, but I already made an test in it, and i'm having trouble to add another validation.

I validate this:

nome: Yup.string()
            .required(Mensagens.CAMPO_OBRIGATORIO)
            .test('teste-nome-igual',Mensagens.NOME_NAO_DEVE_SER_IGUAL,function(value){
                let check = []
                if(contatos.length > 0)
                    check = contatos.map((contato)=> contato.nome.toUpperCase() === value.toUpperCase()) 
                return !check.includes(true)
            }),

But I also want to validate if the field nome doesn't contain any non ASCII caracters, and if so, show a message that it can't contain, things that aren't letters.

like image 336
Matheus Ribeiro Avatar asked Mar 03 '23 21:03

Matheus Ribeiro


1 Answers

You can chain test multiple times as test returns the schema. Like:

Yup.string()
   .required(Mensagens.CAMPO_OBRIGATORIO)
   .test('teste-nome-igual',
         Mensagens.NOME_NAO_DEVE_SER_IGUAL,
         function(value){
           let check = []
           if(contatos.length > 0)
             check = contatos.map((contato)=> contato.nome.toUpperCase() === value.toUpperCase()) 
           return !check.includes(true)
         }
   )
   .test('test ascii',
         "Nome shouldn't contain non-ascii chars",
         (value) => {
         // test for ascii chars here and return true or false.
        }
   )
like image 81
Muhammad Ali Avatar answered Mar 05 '23 16:03

Muhammad Ali