搜尋

首頁  >  問答  >  主體

函數傳回true,即使應該回傳false

<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粉514458863P粉514458863470 天前515

全部回覆(1)我來回復

  • P粉682987577

    P粉6829875772023-08-17 10:50:37

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

    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對象,並確保您正在檢查的值符合預期。

    回覆
    0
  • 取消回覆