[英]modifying required for form elements
我想在提交表單之前設置更多條件,使用表單字段的html'required'屬性。 有沒有辦法可以手動攔截/更改它檢查的條件? 在我的情況下,我想要一個字段作為數組的值。
既然你正在使用React(以及JSX),你可以這樣做:
const myComp = (props) => {
const [isRequired, setIsRequired] = useState(true);
if(your logic for when isRequired should be true here){
setIsRequired(false)
}
return (
<div>
<form required={isRequired} />
</div>
)
}
你可以檢查你想要檢查的任何數據, if
,有多個ifs,多個檢查,一系列檢查,你想要什么。 我將默認設置為true,但您可以按照自己的意願執行此操作。 甚至有默認的邏輯isRequired
值是一些具體的事情。
我在這里使用了required
html屬性,但你也可以攔截onSubmit
表單事件並在那里進行自己的檢查並向用戶解釋剩下要做的事情。
您可以掛鈎onsubmit事件
<form onsubmit="return checkYourCondition()">
<form>
function checkYourCondition(){
//return true or false depending on your condition
return true;
}
您可以生成包含所有數組值的RegEx,並將input
的pattern屬性設置為此RegEx。
使用此解決方案,如果所需輸入無效,您將擁有瀏覽器的默認行為。 (例如突出顯示輸入,通知用戶,......)
這是一個有點冗長的過程,但非常有用。 您可以在form
中的任何input
標記上進行on change
事件,
<input type="text" className="form-control" onChange={(event) => this.handleUserInput(event)} name="fname"/>
handleUserInput(e) {
const name = e.target.name;
const value = e.target.value;
this.setState({[name]: value},
() => { this.validateField(name, value) });
}
validateField(fieldName, value) {
let fnameValid = this.state.fnameValid;
switch(fieldName) {
case 'fname':
fnameValid = value!=="" && /^([a-zA-Z]+)$/.test(value) && value.length >= 2; //here you can check as many condition as you want using `&&` operator.
break;
case 'more input name here':
... // More input validation
break;
default:
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.