I am struggling with how to display error messages underneath form elements. I have a simple HTML, CSS form and form validation using javascript.
I have written some js to generate an error msg if the user doesnt enter text which seems to work ok. However i need to be able to display each error message under each form field and style it. Anyone who can help with this would be great. Its my first time trying to incorporate js into a web page. Here is my repo.
Hey @gemma2301, every input in your form has to be an object with validate() method, which is going to trigger message() method in no-valid case. Then on submit you would run validate() for each input and if every() respond with true - proceed
Ok so he hasnt actually aswered the question I believe. The problem is the positioning of the text not the validation. I have not used the validation method he has suggested but there is nothing wrong with my approach i believe. Also I would like to know what is the problem is with asking for an example? It is a learning platform after all.
As per the original message, I am struggling to display form validation error messages underneath form elements. A simple and common task. I just havent done it before hence i asked for help. I can provide a code example.
Hey @gemma2301, the problem with your code that you have one array of messages and if you want to display each message under corresponding input field that’s obviously not enough. Conceptually, error message should be a matter of input rather than parent form (even though some people might disagree).
Plus, pushing message looks like unnecessary step to me, you can just display message on that step.
So, example:
function appendMsg(element, msg) {
const parent = element.parentElement;
const p = document.createElement('p');
p.classList.add('input-msg');
p.textContent = msg;
parent.appendChild(p);
return true;
}
function removeMsg(element) {
const parent = element.parentElement;
const msg = element.closest('.input-msg');
if (msg.parentElement !== parent) return false;
parent.removeChild(msg);
return true;
}
...
if (firstname.value === '' || firstname.value == null) {
appendMsg(firstname, 'Firstname cannot be empty');
}