@amalkarim
Posted
Hi Gabriel,
What do you mean by unable to make the form submit? I mean, your solution works like a charm. I don't see any problem with it. Could you elaborate more? If you want to really submit the form to any backend server, for example, than you have to remove e.preventDefault();
in this code below, as it will prevent the form to be submitted.
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
But maybe you can explain more about your problem.
@Tzienom
Posted
@amalkarim
Hi, Amal.
So, I just commented out the "e.preventDefault()". Please check it out and see that if you fill some inputs correctly and ignore some, it will still submit the form (reload the page, and that's like submitting the form, yeah?). Now, that's what I want to prevent from happening. I only want it to reload the page when everything's been filled out correctly.
Or you could help explain (or link me to) how a form submission really works, cos I don't know anything on backend.
@amalkarim
Posted
@Tzienom
I see. So basically, the flow of the form will look like this:
- User fill the form
- Client-side validation (using JavaScript) will validate the fields.
- If there's a field or there are fields that don't follow the rules, form won't be submitted
- If all fields are filled properly, the form will be submitted
- Backend server will validate the data again using its own validator, because client side validation could be altered by the user, thus the data must be treated like it's not validated yet.
- In the end, the backend server will process the submitted form and do whatever the programmer want to do with the data
From your code, I see that you created function checkInputs()
. That's one step in the right direction. The only thing you need to do is preventing the form submission when there's an error in any field by calling e.preventDefault()
. When user inputs are okay, do not call e.preventDefault()
and let the form submitted.
Add a conditional return
statement in the bottom of function checkInputs()
, like this:
function checkInputs() {
...
...
if (firstNameValue === "" || regName.test(firstNameValue) || lastNameValue === "" || regName.test(lastNameValue) || emailValue === "" || passwordValue === "") {
return false;
}
return true;
}
Then change the event listener to this:
form.addEventListener('submit', (e) => {
if (!checkInputs()) e.preventDefault();
});
I'm sure we could improve the JavaScript code, but for now it's enough to do its job properly.
There are also many things that must be considered regarding the form and its submission (along with the backend server). But it's outside the scope of this challenge, so it's probably better to move on to the next challenge.
That's it. Hope this helps. Happy coding
@Tzienom
Posted
@amalkarim
Thanks a whole lot. It works perfectly now.
@amalkarim
Posted
@Tzienom great to know!
Feel free to click Mark as helpful button if you find it helpful. See you around
Marked as helpful