Home > Blockchain >  jQuery ohny fire when Form is valid in browser
jQuery ohny fire when Form is valid in browser

Time:05-25

I'm trying to get a jQuery event to only fire once the Form is valid - not using any extensions. For example I have an email field:

<input type="email"  id="email" placeholder="[email protected]" aria-describedby="emailHelp"  name="email" maxlength="250" required>

Inside a Form. Once the submit button is clicked, this event fires:

    $("#submitForm").click(function() {
        $("#spinnerSubmit").removeAttr('hidden');
    });

But if the user does not put an correct email in the right format, the event fires but the Form still waits for an email input. Can i somehow check if the form is validated browser-sided, without using any overkill extensions? Or is my only option this?

CodePudding user response:

Most existing answers, especially tagged will point you to jquery validation.

HTML5 includes some form validation, see: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Constraint_validation#constraint_validation_process

In summary (of that page), you can call checkValidity on a DOM element or form, eg:

document.getElementById("myForm").checkValidity();

Here's an example (jquery just used for events/UI):

$("#submitForm").click(function() {
  var isValid = document.getElementById("myForm").checkValidity();
  
  $("p").text(isValid);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
  <input type="email"  id="email" placeholder="[email protected]" aria-describedby="emailHelp" name="email" maxlength="250" required>
</form>
<button type='button' id='submitForm'>click me</button>
<p>waiting for click</p>

You could also use $("#myForm")[0].checkValidity() but left that out of the example to save confusion over jquery/DOM and [0] or use vanilla for the UI updates.

  • Related