Home > Net >  Joi validation react .custom() validation in react
Joi validation react .custom() validation in react

Time:12-10

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

CodePudding user response:

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: "[email protected]",
  firstName: "adfsdafsdf",
  lastName: "asdfasdf",
  description: "Bitcoin111"
});

CodePudding user response:

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

  • Related