Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

929
Visualizações
How to cast a string into an array using Yup

So whenever I receive a string I want to store it as an array. But I've got no luck so far, i tried to do with cast and with transform. I just need some clarity to get the things going.

Is transform and cast the same thing? How to cast a string into an array using Yup?

const schema = yup.object().shape({
        types: yup
           .array('type must be an array.')
           .of(
                yup
                   .string('the array must contains only strings.')
                   .transform(value =>
                      typeof value === 'string' || value instanceof 'string'
                           ? [value]
                           : value,
                   )
                   .matches(/(writer|artist)/, null),
           )
           .min(1, 'Need to provide at least one type')
           .max(2, 'Can not provide more than two types'),
        name: yup
           .string('name must be a string.')
           .min(3, 'too short'),
      
    });

let obj = {
      name: 'Kentarou Kishima',
      types: 'artist',
}
//returns ValidationError
obj = schema.cast(obj, { stripUnknown: true });

//trying to just validate results in the same error
schema
        .validate(obj)
        .then(() => {     
              
            next();
        })
        .catch(function (e) {
            console.log(e);
            return something;
        });

ValidationError: types must be a array type, but the final value was: null (cast from the value "artist")

Edit: I fixed minor typo btw. Well, I removed the matches line and it keeps returning the same Error. So now I am thinking since it's receiving a string and not an array, when it goes into the transform function it is going to search for the array items to cast, but there's none because it got a string. So it's well likely that the transform function should be side-by-side with array() and not inside it.

The code looks like this now, but I'm still getting the Error with or without matches():

.array('types must be an array.')
        .of(
            yup
                .string('the array must contains only strings.')
                .matches(/(^writer$|^artist$)/) //I improved the regex pattern                
        )
        .transform(value =>
            typeof value === 'string' || value instanceof String
                ? [value]
                : value,
        )
        .min(1, 'Need to provide at least one type')
        .max(2, 'Can not provide more than two types'),

To make things clearer, these are the type of input I am expecting:

let obj = {
      name: 'Kentarou Kishima',
      types: 'artist', //should cast
      types: ['artist'], //should pass
      types: ['artist', 'writer'], //should pass

      types: '', //should reject
      types: ['something'], //should reject
      types: ['artist', 'something', 'writer'], //should reject
      types: ['artist', 'artist'], // should reject, but i will put a test() later on.  

}

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

After messing around with the documentation I found the answer. In this case is enough to use the ensure() function, basically it will take anything that is not an array and put it into an array. After that, the matches() function will reject anything that does not follow the regex pattern.

yup
        .array('types must be an array.')        
        .of(
            yup
                .string('the array must contains only strings.')
                .matches(/(^writer$|^artist$)/)                
        )
        .ensure()
        .min(1, 'Need to provide at least one type')
        .max(2, 'Can not provide more than two types'),

Edit: Just a disclaimer, the way it is with min(1) enabled, this property always will be required even though there's no required(), even specifying notRequired() in the object doesn't do the trick.

This is a known issue in yup https://github.com/jquense/yup/issues/1267

In my case, I need this validator for my POST (all required) and PUT (at least one required) requests, in POST requests I use it the way it is, in PUT requests I dynamically add the rules checking for those present in the req.body.

about 4 years ago · Juan Pablo Isaza Relatório

0

The order of operations on the types property is out of order. It follows:

  1. Ensure array element is string.
  2. If the value is a string, convert it to an array containing itself.
  3. If the array of the single string matches the regular expression, continue. If it does not, report null.

If you truly want an array of single-element arrays, then you can keep the transform, but you'll want to move the matches() above the transform() as the arrays that result from the transform() will never match the regular expression, and so matches() always returns your null.

const schema = yup.object().shape({
        types: yup
           .array('type must be an array.')
           .of(
                yup
                   .string('the array must contains only strings.')
                   .matches(/(writer|artist)/, null)
                   .transform(value =>
                      typeof value === 'string' || myVar instanceof 'string'
                           ? [value]
                           : value,
                   ),
           )
           .min(1, 'Need to provide at least one type')
           .max(2, 'Can not provide more than two types'),
        name: yup
           .string('name must be a string.')
           .min(3, 'too short'),
      
    });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda