Multiple validation on one field Yup

13.1k views Asked by At

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.

1

There are 1 answers

2
Muhammad Ali On BEST ANSWER

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.
        }
   )