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.
may be caused by using a mixture of
==
and===
. I recommend trying the following code first: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.