Home > database >  How to modify data after validation in React form
How to modify data after validation in React form

Time:03-08

I have a simple form where the user can input a url like example, example.com or https://example.com. I only accept example.com but I want to keep the user free to write what he want.

I wrote a simple onSubmit handler in order to check the domain the user wrote:

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>

The validation success, but if the user input example without the .com ecc, the form send ?domain=example.

I would like the form to send the data I set with the .com, how is It possible?

CodePudding user response:

A useState did the trick.

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

  • Related