我有一個簡單的表單,用戶可以在其中輸入一個 url,如example,example.com或https://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沒有.comecc,則form發送?domain=example.
我想要表格發送我用 設定的資料.com,這怎么可能?
uj5u.com熱心網友回復:
AuseState成功了。
setInputValue(completeUrl.split("//")[1])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439912.html
上一篇:使用現有答案作為提示文本
下一篇:如何指定我的先例表格的物件?
