L
L
lorentso2021-07-09 19:17:05
JavaScript
lorentso, 2021-07-09 19:17:05

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);
  }

});


I connect the script before closing the body tag, I made sure that the corresponding elements have the _req check class. What is wrong - I can not understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-07-09
@lorentso

formRemoveError('input');
Quotes are not needed here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question