Design comparison
Solution retrospective
Greeting guys, this is my solution for the form validation challenge. can you take a look and share with me how to improve it specially I need to validate the form after an error without refreshing the page. Your help will be appreciate. Thanks in advance
Community feedback
- @hejkeikeiPosted over 2 years ago
Hi Stephane, For preventing refresh the page, you can use
event.preventDefault();
in your event listener. MDNAlso, you can use
getAttribute()
so that you don't have to write things manually. In that case, you can use loop so you won't have to repeat your code:) For example:<input type="text" name="fname" id="fname" placeholder="First Name" required/>
then you can do this:
const fields = document.querySelectorAll("input"); for(let i=0; i< fields.length-1; i++){ if(fields[i].value==""){ fields[i].nextElementSibling.innerHTML=fields[i].getAttribute("placeholder")+" cannot be empty"; //output => First Name cannot be empty }else{ fields[i].nextElementSibling.innerHTML=""; } }
For detail information please see here
Marked as helpful0@distephano30Posted over 2 years ago@hejkeikei Hi Ting-Huei, Many thanks! you helped found out what's wrong. I added the preventdefault and also the first time I missed the innerHTML="" which would keep the error blank if input is good. Ny the way, i like the simplicity of your code, I wrote a lot of lines of code, but yours is so simple 😀😀😀. Thank you again.
0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord