(function() {
// Function to handle form submission errors
function handleFormSubmissionError(form) {
// Check if the form has an error
if (form.checkValidity()) {
return; // No errors, do nothing
}
// Get the form's validation errors
const errors = form.elements;
const errorMessages = [];
for (let i = 0; i < errors.length; i++) {
const element = errors[i];
if (element.checkValidity() === false && element.validationMessage) {
errorMessages.push(element.validationMessage);
}
}
// Log the errors to the server (replace with your API endpoint)
if (errorMessages.length > 0) {
console.error("Form Submission Error:", errorMessages.join(", "));
// Send data to server (example using fetch)
fetch('/api/form-error', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
formName: form.name, // Name of the form
errors: errorMessages.join(", ") // Errors as a string
})
})
.then(response => {
if (!response.ok) {
console.error("Error sending form error to server:", response.status);
}
});
}
}
// Attach the event listener to the form
document.addEventListener('DOMContentLoaded', function() {
const forms = document.querySelectorAll('form'); // Select all forms
forms.forEach(form => {
form.addEventListener('submit', function(event) {
// Prevent default form submission behavior
event.preventDefault();
// Handle errors after preventing submission
handleFormSubmissionError(this);
});
});
});
})();
Add your comment