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

234
Visualizações
Joi validation react .custom() validation in react

Hello I'm trying to add custom validation to my form using the Joi library.Basically i want to reach to an api and either return error message or not based on the data. here is my Joi schema

  const schema = Joi.object({
    email: Joi.string()
      .email({ tlds: { allow: false } })
      .required(),
    firstName: Joi.string().required(),
    lastName: Joi.string().required(),
    description: Joi.string().min(10).max(250).required().custom(isSad).message({'description.invalid':`the value provided in the description field is sad, please redact it`}),
  });

the isSad function passed in the custom() argument

  const isSad =  (value,helpers) => {
    fetch('api url',{
      method: "POST",
      headers: {
        "apikey": "key"
      },
      body:value 
    }).then(data => {
      return data.json()
    }).then(data => {
      
      if(data.Sad > 0.49) {
        return helpers.error('description.invalid');
      }
    }).catch(error => {
      console.log('logging the error in catch', error)
    })
  }

As far as I understand I'm sending 'description.invalid' to the .message() function in the schema where I should use it in the passed object to display a custom message, but for some reason I'm not getting the error message displayed. The field seems to be validated as valid which it shouldn't be in my case if the value received is > 0.49

EDIT: Tried using schema.validateAsync with .external() like so

  const isSad =  (value,helpers) => {
    console.log('logging value',value)
    console.log('logging helpers',helpers)

    fetch('api',{
      method: "POST",
      headers: {
        "apikey": "apikey"
      },
      body:value 
    }).then(data => {
      return data.json()
    }).then(data => {
      if(data.Sad > 0.49) { 
        throw new Error('Ur description is sad please edit it')
      }
    }).catch(error => {
      console.log('logging the error in catch', error)
    })
  }

and to the schema i just attach .external(isSad) like so

  const schema = Joi.object({
    email: Joi.string()
      .email({ tlds: { allow: false } })
      .required(),
    firstName: Joi.string().required(),
    lastName: Joi.string().required(),
    description: Joi.string().min(10).max(250).required().external(isSad)
});

I also had to convert the code where I use the schema.validateAsync since it now returns data as HTTP response.BUT it still doesn't work I get no response whatsoever from the .external() and the description field is validated ( It's like the .external() is not there at all ).

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

0

Found an issue, it says that custom is only for synchronous functions, for async you need to use external.


EDIT1

If I understand it right, and please correct me if not, the problem is that error is not thrown, when it should.
In that case I have done the following. Changed the request and the data.
The console says: logging the error in catch Error: Ur description is sad please edit it. Which looks to me as the expected behavior.

const isSad = (value) => {
  console.log("value: ", value);

  fetch("https://api.coindesk.com/v1/bpi/currentprice.json", {
    method: "GET"
  })
    .then((data) => data.json())
    .then((data) => {
      console.log("request data: ", data);
      if (value.startsWith(data.chartName)) {
        throw new Error("Ur description is sad please edit it");
      }
    })
    .catch((error) => {
      console.log("logging the error in catch", error);
    });
};

const schema = Joi.object({
  email: Joi.string()
    .email({ tlds: { allow: false } })
    .required(),
  firstName: Joi.string().required(),
  lastName: Joi.string().required(),
  description: Joi.string().min(10).max(250).required().external(isSad)
});

schema.validateAsync({
  email: "asf@adf.asdf",
  firstName: "adfsdafsdf",
  lastName: "asdfasdf",
  description: "Bitcoin111"
});
about 4 years ago · Juan Pablo Isaza Relatório

0

I ended up using .validate() not .validateAsync() and made my own custom function check after Joi has already validated the form.

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