Skip to content

Instantly share code, notes, and snippets.

@anupammaiti
Created October 23, 2024 22:57
Show Gist options
  • Select an option

  • Save anupammaiti/a1a8b32eb8ebf44859f6c3de4fc24ed9 to your computer and use it in GitHub Desktop.

Select an option

Save anupammaiti/a1a8b32eb8ebf44859f6c3de4fc24ed9 to your computer and use it in GitHub Desktop.

Revisions

  1. anupammaiti created this gist Oct 23, 2024.
    26 changes: 26 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    form.addEventListener('submit', function(event) {
    event.preventDefault();

    let hasErrors = false;

    // Loop through each form element
    [...form.elements].forEach(input => {
    if (!input.checkValidity()) {
    console.log(`Error in field: ${input.name}`);
    hasErrors = true;

    // Optionally, show custom error messages
    input.setCustomValidity('This field is invalid!');
    } else {
    input.setCustomValidity(''); // Clear any custom error messages
    }
    });

    if (hasErrors) {
    form.reportValidity(); // Show validation errors in the UI
    console.log('Form has errors.');
    } else {
    console.log('Form is valid. Proceeding with submission.');
    // form.submit(); // You can proceed with form submission here
    }
    });