36

I have a simple HTML form that I want to leverage for required field validation. My issue is that I want to use the HTML5 form validation BUT at the same time avoid actually submitting the form because I want to execute a jQuery Ajax call instead. I know you can disable html5 validation, but I want to keep this as my primary method of form validation instead of a jQuery plugin.

Any thoughts?

HTML

<form action="donothing" id="membershipform" method="get" accept-charset="utf-8">
    <input type="text" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="first and last name" required>
    <input type="email" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="email" required>
    <input type="phone" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="phone" required>    
    <input type="phone" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="mailing address" required>      
    <input type="phone" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="how you heard about us" required>
    <p>
        <input type="submit" id="submitbtn" class="submitbtn" value="Continue" style="width:265px">
    </p>
</form> 

JavaScript:

$(function(){
  $("#submitbtn").click(function(){
    $.ajax({
      url: "<?php bloginfo('template_url') ?>/ajax-membership.php",
      success: 
      function(txt){
        if(txt){
          $("#thankyou").slideDown("slow");
        }
      }
    });
  });
});
TylerH
  • 20,799
  • 66
  • 75
  • 101
Rees
  • 1,757
  • 9
  • 33
  • 50

5 Answers5

57

According to this: Do any browsers yet support HTML5's checkValidity() method?, and this may not be the latest truth since HTML5 is a work in progress, the Form.checkValidity() and element.validity.valid should let you access validation information from JavaScript. Assuming that's true, your jQuery would need to attach itself to the form submit and make use of that:

$('#membershipform').submit(function(event){
    // cancels the form submission
    event.preventDefault();

    // do whatever you want here
});
Community
  • 1
  • 1
Milimetric
  • 13,411
  • 4
  • 44
  • 56
  • To all readers: MAKE SURE to include the event parameter in the function, otherwise this WILL NOT work in Firefox. – Marcel Gruber Mar 26 '15 at 21:42
  • 1
    @Max, do you mean to make sure to pass the `event` parameter to the callback function? If so, yes, that's certainly required in all browsers as you couldn't call `preventDefault` otherwise. – Milimetric Mar 26 '15 at 22:05
  • Yes. Just as a reminder. I wasted a good bit of time trying to figure out why it wasn't working after just using the `event.preventDefault();` and not the rest of the example. Even without the `event` parameter, it still seemed to behave as desired on Chrome, but not Firefox. – Marcel Gruber Mar 26 '15 at 22:14
  • 1
    @Max - what you might have there is that Chrome automatically has some automatic validation behavior that also prevents the submitting of the form. So this code would not be needed at all, but `event.preventDefault()` would throw an error on the console if you were using it without `event` being defined. So make sure to keep that console open. Stay safe out there! :) – Milimetric Mar 27 '15 at 12:11
14

You can use html5 form validation from javascript, only call to method reportValidity()

In your example:

<script>
    document.querySelector('#membershipform').reportValidity()
</script>

reportValidity run html5 form validation and return true/false.

Eduardo Antón
  • 141
  • 1
  • 3
4

This is a subtle leverage of default behaviour and javascript to create what you want.

var form = document.getElementById("purchaseForm");
if(form.checkValidity()){
    console.log("valid");
    e.preventDefault();
}else{
    console.log("not valid");
    return;
}

If the form is valid then preventDefault() and continue with your function (e.g. send over ajax). If not valid then return without preventing default, you should find the default actions for form validation occurs on your form inputs.

benbyford
  • 603
  • 1
  • 8
  • 18
  • This worked for me. It helped me check if all input fields were valid. I did not use `e.preventDefault();`, instead, I put my code that stored the form in the `if` statement. – Vini Sep 08 '19 at 20:13
4

Use:

$('#membershipform').submit(function(){
    // do whatever you want here

    return false;
});
Darm
  • 5,581
  • 2
  • 20
  • 18
  • 3
    This won't work if the code above the return statement throws an error. In case of an error the form still go to the address specified in the "action" attribute. – Stan Jan 11 '13 at 00:28
  • Yes! this works if I want my form to go through the validation part but not submit. good job – Sando K Jan 09 '16 at 18:00
1

Using pure java script

<script>

    document.getElementById('membershipform')
        .addEventListener("submit", 
            function(event) {
                event.preventDefault();

                // write stuff

            });

</script>
J.D. Mallen
  • 4,339
  • 3
  • 22
  • 33
Chirag
  • 1,478
  • 16
  • 20