const showInputError = (formElement, inputElement, errorMessage, inputError, errorClass) => {
const errorElement = formElement.querySelector(`.${inputElement.id}-error`);
inputElement.classList.add(inputError);
errorElement.textContent = errorMessage;
errorElement.classList.add(errorClass);
};
const hideInputError = (formElement, inputElement, inputError, errorClass) => {
const errorElement = formElement.querySelector(`.${inputElement.id}-error`);
inputElement.classList.remove(inputError);
errorElement.textContent = "";
errorElement.classList.remove(errorClass);
};
const isValid = (formElement, inputElement, inputError, errorClass) => {
if(!inputElement.validity.valid){
showInputError(formElement, inputElement, inputElement.validationMessage, inputError, errorClass);
} else {
hideInputError(formElement, inputElement, inputError, errorClass);
}
}
const setEventListenersForm = (formElement, validationConfig, inputError, errorClass) => {
const inputList = Array.from(formElement.querySelectorAll(validationConfig.inputSelector));
inputList.forEach((inputElement) => {
inputElement.addEventListener("input", () => {
isValid(formElement, inputElement, inputError, errorClass)
})
})
}
const enableValidation = (validationConfig) => {
const formList = Array.from(document.querySelectorAll(validationConfig.formSelector));
formList.forEach((formElement) => {
setEventListenersForm(formElement, validationConfig)
})
}
enableValidation({
formSelector: '.popup__form',
inputSelector: '.popup__input',
inputErrorClass: 'popup__input_type_error',
errorClassActive: 'popup__input-error_active',
});
.popup__input-error {
font-weight: 400;
font-size: 12px;
color: #f00;
opacity: 0;
}
.popup__input-error_active {
opacity: 1;
}
.popup__input_type_error {
border-bottom: 1px solid #ff0000;
}
<div class="popup popup_type_edit popup_is-animated">
<div class="popup__content">
<button type="button" class="popup__close"></button>
<h3 class="popup__title">Редактировать профиль</h3>
<form class="popup__form" name="edit-profile" novalidate>
<input type="text" name="name" class="popup__input popup__input_type_name" id="name-input" placeholder="Имя" required minlength="2" maxlength="40">
<span class="popup__input-error name-input-error"></span>
<input type="text" name="description" class="popup__input popup__input_type_description" id="text-input" placeholder="Занятие" required minlength="2" maxlength="200">
<span class="popup__input-error text-input-error"></span>
<button type="submit" class="button popup__button">Сохранить</button>
</form>
</div>
</div>