如何在 React 表单验证后修改数据

How to modify data after validation in React form

我有一个简单的表单,用户可以在其中输入 url,例如 exampleexample.comhttps://example.com。我只接受 example.com 但我想让用户自由地写他想写的东西。

我写了一个简单的 onSubmit 处理程序来检查用户写的域:

const handleSubmit = (event: React.SyntheticEvent) => {
  setIsBusy(true);
  const target = event.target as typeof event.target & {
    domain: { value: string };
  };
  const domain = target.domain.value;
  const hasSuffix = domain.endsWith(".com");
  const hasHttpPrefix =
    domain.startsWith("http://") || domain.startsWith("https://");
  const completeUrl = `${hasHttpPrefix ? "" : "https://"}${domain}${
    hasSuffix ? "" : ".com"
  }`;

  const domainRegex =
    /^(https|http)\:\/\/[a-zA-Z0-9][a-zA-Z0-9\-]*\.com/;
  if (!domainRegex.test(completeUrl)) {
    event.preventDefault();
    setIsBusy(false);
    setIsError(true);
  }

  // now the form should submit ?domain=example.com
  target.domain.value = `${completeUrl.split("//")[1]}`;
};

<form method="get" onSubmit={handleSubmit} action="/">...</form>

验证成功,但是如果用户输入example没有.com ecc,form发送?domain=example.

我想要表单发送我用 .com 设置的数据,怎么可能?

一个useState成功了。

setInputValue(completeUrl.split("//")[1])