函數傳回true,即使應該回傳false
P粉514458863
2023-08-16 19:57:43
<p>我正在使用NextJS建立一個客戶端表單。我試圖在表單的客戶端上放置驗證,並將其放在單獨的函數中,但每次執行validateForm()函數時,它都會傳回true,而不管輸入如何。我覺得我在這裡漏掉了一些愚蠢的東西,但我正在絞盡腦汁,卻一無所獲。以下是代碼:</p>
<pre class="brush:php;toolbar:false;">const [jobSubmission, setJobSubmission] = useState({});
function handleChange (e){
const jobInputName = e.target.name;
const jobInputValue = e.target.value;
const newJobSubmission = {
...jobSubmission,
[jobInputName]: jobInputValue,
}
console.log(newJobSubmission)
setJobSubmission(newJobSubmission)
}
function validateForm (){
console.log("Validation runnning")
if(jobSubmission.jobCategory == `Please-Select` || jobSubmission.jobCategory === null){
alert("Please make job category selection")
return false
}
if (jobSubmission.salarRange !== null && jobSubmission.timeOfPayment === null){
alert("Please select frequency of salary payment or remove salary range");
return false
}
return true
}
function handleSubmission(){
const isReady = validateForm()
console.log(isReady)
if (isReady === true){
// Add UniqId
const finalJobObject = {
...jobSubmission,
jobId: uniqid()
}
sendJobToDB(finalJobObject)
window.location = "/post-a-job/thank-you"
} else{
alert("Please fill in all required fields")
}
}</pre>
<p>基本上,我想將驗證檢查放在單獨的驗證函數中,並在出現問題時實際返回false。 </p>
<p>我已經嘗試更改如何追蹤布林值,但它始終返回true。 </p>
可能是因為使用了
==
和===
的混合使用所導致的。我建議先嘗試以下程式碼:如果仍然有問題,我建議在控制台日誌中檢查jobSubmission對象,並確保您正在檢查的值符合預期。