函數傳回true,即使應該回傳false
P粉514458863
P粉514458863 2023-08-16 19:57:43
0
1
503
<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>
P粉514458863
P粉514458863

全部回覆(1)
P粉682987577

可能是因為使用了=====的混合使用所導致的。我建議先嘗試以下程式碼:

function validateForm() {
    console.log("Validation running");

    if (jobSubmission.jobCategory === 'Please-Select' || jobSubmission.jobCategory === undefined) {
        alert("Please make a job category selection");
        return false;
    }

    if (jobSubmission.salaryRange !== null && jobSubmission.timeOfPayment === undefined) {
        alert("Please select the frequency of salary payment or remove the salary range");
        return false;
    }

    return true;
}

如果仍然有問題,我建議在控制台日誌中檢查jobSubmission對象,並確保您正在檢查的值符合預期。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板