1. (function() {
  2. // Function to handle form submission errors
  3. function handleFormSubmissionError(form) {
  4. // Check if the form has an error
  5. if (form.checkValidity()) {
  6. return; // No errors, do nothing
  7. }
  8. // Get the form's validation errors
  9. const errors = form.elements;
  10. const errorMessages = [];
  11. for (let i = 0; i < errors.length; i++) {
  12. const element = errors[i];
  13. if (element.checkValidity() === false && element.validationMessage) {
  14. errorMessages.push(element.validationMessage);
  15. }
  16. }
  17. // Log the errors to the server (replace with your API endpoint)
  18. if (errorMessages.length > 0) {
  19. console.error("Form Submission Error:", errorMessages.join(", "));
  20. // Send data to server (example using fetch)
  21. fetch('/api/form-error', {
  22. method: 'POST',
  23. headers: {
  24. 'Content-Type': 'application/json'
  25. },
  26. body: JSON.stringify({
  27. formName: form.name, // Name of the form
  28. errors: errorMessages.join(", ") // Errors as a string
  29. })
  30. })
  31. .then(response => {
  32. if (!response.ok) {
  33. console.error("Error sending form error to server:", response.status);
  34. }
  35. });
  36. }
  37. }
  38. // Attach the event listener to the form
  39. document.addEventListener('DOMContentLoaded', function() {
  40. const forms = document.querySelectorAll('form'); // Select all forms
  41. forms.forEach(form => {
  42. form.addEventListener('submit', function(event) {
  43. // Prevent default form submission behavior
  44. event.preventDefault();
  45. // Handle errors after preventing submission
  46. handleFormSubmissionError(this);
  47. });
  48. });
  49. });
  50. })();

Add your comment