P
P
pnvola2020-04-27 14:11:48
JavaScript
pnvola, 2020-04-27 14:11:48

Why does TypeError: undefined is not an object (evaluating 'this.elements') occur?

class Validation {
  constructor(source) {
    let form = source;
    if (source.nodeName !== "FORM") {
      form = source.querySelector("FORM");
    }

    this.isValid = false;
    this.inputs = form.querySelectorAll(".popup__input");
    this.button = form.querySelector(".popup__button");
    this.error = "";
    this.addInputEventListeners();
    this.addSubmitEventListener();

    this.validate = this.validate.bind(this);
    this.renderError = this.renderError.bind(this);
  }

  addInputEventListeners() {
    for (const input of this.inputs) {
      input.addEventListener("input", this.handleInput.bind(this));
    }
  }

  addSubmitEventListener() {
    this.button.addEventListener("onclick", this.validate.bind(this));
  }

  handleInput(event) {
    const { target } = event;
    const isValid = this.checkInputValidity(target);

    if (!isValid) {
      this.isValid = false;
    }

    this.renderError(target, this.error);
    this.setSubmitButtonState();
  }

  checkInputValidity(element) {
    this.error = this.getErrorFor(element);
    return this.error.length === 0;
  }

  getErrorFor(element) {
    if (element.validity.valueMissing) {
      return "Это обязательное поле";
    }
    if (element.type === "url" && element.validity.typeMismatch) {
      return "Здесь должна быть ссылка";
    }
    if (element.validity.tooLong || element.validity.tooShort) {
      return "Должно быть от 2 до 30 символов";
    }
    return "";
  }

  validate() {
    this.isValid = true;

    for (const element of this.elements) {  //ЗДЕСЬ ВЫЛЕЗАЕТ ОШИБКА (
      const isValid = this.checkInputValidity(element);

      if (!isValid) {
        this.isValid = false;
        break;
      }
    }
  }

  renderError(target, error) {
    target.nextElementSibling.textContent = error;
  }

  setSubmitButtonState() {
    this.validate();

    if (this.isValid) {
      this.button.classList.add("popup__button_enable");
    } else {
      this.button.classList.remove("popup__button_enable");
    }
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question