簡體   English   中英

反應中的 Joi 驗證 react.custom() 驗證

[英]Joi validation react .custom() validation in react

您好,我正在嘗試使用 Joi 庫向我的表單添加自定義驗證。基本上我想訪問 api 並根據數據返回錯誤消息或不返回錯誤消息。 這是我的 Joi 架構

  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`}),
  });

在 custom() 參數中傳遞的 isSad function

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

據我了解,我在架構中向 the.message() function 發送“description.invalid”,我應該在傳遞的 object 中使用它來顯示自定義消息,但由於某種原因我沒有收到錯誤消息顯示的消息。 如果收到的值 > 0.49,該字段似乎被驗證為有效,在我的情況下它不應該是有效的

編輯:嘗試使用 schema.validateAsync with.external() 像這樣

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

並且我只是 attach.external(isSad) 這樣的模式

  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 的地方轉換代碼,因為它現在將數據作為 HTTP 響應返回。但它仍然不起作用我沒有從 the.external() 得到任何響應,並且描述字段已經過驗證(就像the.external() 根本不存在)。

發現一個問題,它說custom僅適用於同步功能,對於 async 你需要使用external

在 Joi 已經驗證了表單之后,我最終使用了.validate() not.validateAsync() 並進行了我自己的自定義 function 檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM