Function returns true even though it should return false
P粉514458863
P粉514458863 2023-08-16 19:57:43
0
1
423

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:

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") } }

Basically, I want to put the validation check in a separate validation function and actually return false if something goes wrong.

I've tried changing how the boolean is tracked but it always returns true.

P粉514458863
P粉514458863

reply all (1)
P粉682987577

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.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!