首页  >  问答  >  正文

函数返回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粉514458863453 天前484

全部回复(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
  • 取消回复