检查该网站是否存在,如果不存在,则在表单输入字段下显示错误消息

Check if the website exists and if not then display Error message under the Form Input Field

我是 JS 和 React 的新手,我正在使用 React Hook Form 我必须检查在我的表单中输入网站字段的网站是否存在。 如果 URL 不存在,我必须在将使用 FormError 组件呈现的网站字段下显示一条错误消息,如“网站不可用”。

(这是一个名字字段,但由于我使用的是通用的 TextField 组件,因此它也应该在这里工作)

所以,我正在使用“url-exists”包来测试网站 URL 是否存在以及该网站是否不存在它应该会生成错误“网站不可用”。

我正在使用此代码来实现。

const websiteCheck = (value) => {
  let str = value;
  let message = "";
    let urlCheck = str.indexOf("http://") == 0 || str.indexOf("https://") == 0;
    if (!urlCheck) {
        console.log("Protocol doesn't exist!");
        str = "http://" + str;
    } else {
        console.log("Protocol exists!");
    }
    urlExists(str, function (err:any, exists:any) {
      if (!exists) {
        message = "Website doesn't exists!" //Just for testing
        console.log("Not available: ", str, exists);
      } else {
        message = "Website exists!"
        console.log("Available: ", str, exists);
    }
        // console.log(exists); // true
    });
  return message;
}

我称它为:

return(
.....
 <TextField
        key={fieldName}
        id={fieldName}
        .......
        inputRef={register({
            websiteCheck(value)
       ........
 />

这在理想情况下应该可以工作,但它在 console.log() 中给我“不可用”消息,即使我输入了正确且有效的 URL。 而且它仍然不会呈现我设置的消息。

到目前为止,我从调试中发现的是:

  1. 当我提交表单时,我输入的 URL 被接受,但它不会进入我的 if(!exists)..else 块,我得到“不可用”在控制台中。
  2. 它第二次提交空值(或 space idk)进入 if(!exists)...else 块并显示“不可用”

我应该怎么做才能解决这个问题?

您必须在此处更正一些内容才能使其正常运行:

  • 在使用 Material UI <TextField /> 时应使用 <Controller />,请参阅文档中的 section 了解更多信息
  • 您需要使用 RHF 通过 <Controller />rules 属性提供的 validate 函数,检查 here 的所有验证选项(registerrules 使用相同的接口进行验证)
  • urlExists 使用回调,因此您需要将对 urlExists 的调用包装到 Promise 中并将其设置为您的 [=20] 的 return 值=] 功能。现在你甚至在执行回调之前 returning 一个字符串。这里重要的是还要让你的 websiteCheck 函数 async,这样 Promise 就会得到解决(RHF 的 validate 函数支持使用 async 函数)
  • 同样重要的是要注意,如果输入的值正确,您必须 return true 用于 validate 函数。如果不使用字符串作为错误消息