Answer the question
In order to leave comments, you need to log in
How to solve 'Cannot read property 'classList' of undefined'' problem?
I am learning how to make a page with form validation. I copy from a lesson on YouTube, it seems to be one to one - I checked it, but the script does not work.
By design, the script should check inputs with the _req class and add the _error class to fields that have not passed validation, highlighting in red, but nothing happens. The browser gives an error:
Cannot read property 'classList' of undefined'
The script at this stage looks like this
"use strict"
document.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById('form');
form.addEventListener('submit', formSend);
async function formSend(e) {
e.preventDefault();
let error = formValidate(form);
}
function formValidate(form) {
let error = 0;
let formReq = document.querySelectorAll('._req');
for (let index = 0; index < formReq.length; index++) {
const input = formReq[index];
formRemoveError('input');
if (input.classList.contains('_email')) {
if (emailTest(input)) {
formAdError(input);
error++;
}
} else if(input.getAttribute("type") === "checkbox" && input.checked === false) {
error++;
} else {
if(input.value === '') {
formAddError(input);
error++;
}
}
}
}
function formAddError(input) {
input.parentElement.classList.add('_error');
input.classList.add('_error');
}
function formRemoveError(input) {
input.parentElement.classList.remove('_error');
input.classList.remove('_error');
}
function emailTest(input) {
return !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/.test(input.value);
}
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question