Home  >  Q&A  >  body text

Function returns true even though it should return false

<p>I'm using NextJS to create a client-side form. I'm trying to place validation on the client side of the form and put it in a separate function, but every time I run the validateForm() function it returns true regardless of the input. I feel like I'm missing something stupid here, but I'm racking my brain and getting nowhere. Here is the code: </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 running") 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>Basically, I want to put the validation check in a separate validation function and actually return false if something goes wrong. </p> <p>I've tried changing how the boolean is tracked but it always returns true. </p>
P粉514458863P粉514458863452 days ago482

reply all(1)I'll reply

  • P粉682987577

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

    may be caused by using a mixture of == and ===. I recommend trying the following code first:

    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;
    }
    

    If the problem persists, I recommend checking the jobSubmission object in the console log and making sure the value you are checking is as expected.

    reply
    0
  • Cancelreply