I'm trying to use this data validation code using JavaScript from the freeCodeCamp website to implement into my code, but when I test the code itself in vscode using a live browser, it doesn't work, but works well in jsfiddle. I'm not sure why it doesn't work well in a browser?
freeCodeCamp article i got it from:https://www.freecodecamp.org/news/form-validation-with-html5-and-javascript/
freeCodeCamp jsfiddle code https://jsfiddle.net/0tq3e49w/4/
Html code:
<form id="form">
<label for="firstname"> First Name* </label>
<input type="text" name="firstname" id="firstname" />
<button id="submit">Submit</button>
<span role="alert" id="nameError" aria-hidden="true">
Please enter First Name
</span>
</form>
JS code:
const submit = document.getElementById("submit");
submit.addEventListener("click", validate);
function validate(e) {
e.preventDefault();
const firstNameField = document.getElementById("firstname");
let valid = true;
if (!firstNameField.value) {
const nameError = document.getElementById("nameError");
nameError.classList.add("visible");
firstNameField.classList.add("invalid");
nameError.setAttribute("aria-hidden", false);
nameError.setAttribute("aria-invalid", true);
}
return valid;
}
CSS code:
#nameError {
display: none;
font-size: 0.8em;
}
#nameError.visible {
display: block;
}
input.invalid {
border-color: red;
}
CodePudding user response:
You add a condition if the field is invalid but you didn't add a condition if the field is valid to reset the invalid styles.
const submit = document.getElementById("submit");
submit.addEventListener("click", validate);
function validate(e) {
e.preventDefault();
const firstNameField = document.getElementById("firstname");
if (!firstNameField.value) {
const nameError = document.getElementById("nameError");
nameError.classList.add("visible");
firstNameField.classList.add("invalid");
nameError.setAttribute("aria-hidden", false);
nameError.setAttribute("aria-invalid", true);
} else {
firstNameField.classList.remove("invalid");
nameError.classList.remove("visible");
nameError.setAttribute("aria-hidden", true);
nameError.setAttribute("aria-invalid", false);
}
}
#nameError {
display: none;
font-size: 0.8em;
}
#nameError.visible {
display: block;
}
input.invalid {
border-color: red;
}
<form id="form">
<label for="firstname"> First Name* </label>
<input type="text" name="firstname" id="firstname" />
<button id="submit">Submit</button>
<span role="alert" id="nameError" aria-hidden="true">
Please enter First Name
</span>
</form>