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