const MAIL_PATTERN = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/; function validateField(selector, errorSelector, validationFn) { const value = $(selector).val().trim(); const isFieldValid = validationFn(value); if (!isFieldValid) { $(errorSelector).addClass("is-visible"); // Show error } else { $(errorSelector).removeClass("is-visible"); // Hide error } return isFieldValid; } function isEmailValid(email) { return MAIL_PATTERN.test(email); } // Show an error when the user leaves the email field (blur) $("#email").on("blur", function() { validateField("#email", ".email-error", isEmailValid); }); // Hide the error when the user starts editing the email (input) or focuses on the email field (focus $("#email").on("focus input", function() { $(".email-error").removeClass("is-visible"); }); $("#name").on("focus input", function() { $(".name-error").removeClass("is-visible"); }); $("#message").on("focus input", function() { $(".message-error").removeClass("is-visible"); }); $("#contact_form").on("submit", function (event) { event.preventDefault(); // Override the default form behavior // Fields validation const nameIsValid = validateField("#name", ".name-error", (val) => val.length > 0); const emailIsValid = validateField("#email", ".email-error", isEmailValid); const messageIsValid = validateField("#message", ".message-error", (val) => val.length > 0); const isValid = nameIsValid && emailIsValid && messageIsValid; // Send the form if all fields are valid if (isValid) { const data = { name: $("#name").val().trim(), email: $("#email").val().trim(), message: $("#message").val().trim(), }; // Send data to the server using AJAX $.ajax({ url: "/send", // URL of the server handler type: "post", headers: {"Reply-To": data.email}, data: data, success: function () { // Processing of successful data sending showPopupMessage("popupSuccessMessage"); $('form input[type="text"], form input[type="email"], form textarea').val( "", ); }, error: function (error) { // Handling errors showPopupMessage("popupFormSubmitFailed"); console.error("Error during data sending: ", error); }, }); } });