How to force an HTML form to validate without submitting it via jQuery
Asked Answered
M

21

350

I have this form in my app and I will submit it via AJAX, but I want to use HTML for client-side validation. So I want to be able to force the form validation, perhaps via jQuery.

I want to trigger the validation without submitting the form. Is it possible?

Meaning answered 8/8, 2012 at 14:37 Comment(3)
Can you specify at which point would you like to validate the form? What triggers the validation? Do you want to validate each field when user types, enters/leaves field, changes value?Downstroke
I would like to be possible to do something like that: $("#my_form").triggerHtml5Validation()Meaning
This page might help linkOireachtas
B
519

To check whether a certain field is valid, use:

$('#myField')[0].checkValidity(); // returns true|false

To check if the form is valid, use:

$('#myForm')[0].checkValidity(); // returns true|false

Show html5 built-in error

if (! $('#myForm')[0].checkValidity()) {
      $('#myForm')[0].reportValidity()
}

Keep in mind that, HTML5 validation is not supported in all browsers till now.

Branum answered 8/8, 2012 at 14:42 Comment(17)
No, I want to trigger the validation without submitting the form.Meaning
I tried your solution, but it still submit the form when $myForm.submit() line is executed.Bigham
Try replacing $myForm.submit() with $myForm.find(':submit').click()Branum
Abraham is correct. You have to actually click the submit button (programmatically). Calling $myForm.submit() will not trigger the validation.Husky
If your form doesn't have a submit button, you can fake one: $('<input type="submit">').hide().appendTo($myForm).click().remove();Dibrin
I have some form validation in if statement condition. Please have a look here: #27678987Mazy
This answer is very useful because of the tip about checkValidity(), but it also has a dangerous error. checkValidity() is what triggers native browser error messages, not the clicking of the submit button. If you have an event listener that listens to the clicking of the submit button, you'll trigger it when you do ` $myForm.find(':submit').click()`, which will trigger itself and cause infinite recursion.Mcphail
You can have a hidden submit button that you can use exclusively to trigger the validation messages. This would remove the dangerous error noted by @kitkat, wouldn't it?Neoteric
I'm not sure it helps if the submit button is hidden. It's having a submit event listener that makes it dangerous, whether the submit button is visible or not. In any case, clicking 'submit' isn't what triggers the validation, so it's kind of a moot point.Mcphail
In my chrome, dd 2015/07, form.checkValidity() by itself does not trigger the gui error messages. $form.submit() and $form.triggerHandler('submit') do not trigger the gui messages ether. A click on a submit button, wether hidden or generated temporary, does trigger the gui. Just make sure ofcourse you don't accidently loop the validation yourself.Bumblebee
This can be achieved without jQuery. See my solution.Oireachtas
Here's a JS Bin that demonstrates the usage and some interesting examples of what should and should not be valid addresses: jsbin.com/jaxasorevu/edit?js,outputTantalous
This worked form me to display the native HTML 5 error messages with form validationFablan
You man are a life saver! Didn't knew the difference between click() and submit(). I love you SO!Foundry
After form validation and the ajax form submit wants to take over i keep getting this error: "Synchronous XMLHttpRequest on the main thread is deprecated". Walkaround I used is this if (!$myForm[0].checkValidity()) { // If the form is invalid, submit it. The form won't actually submit; // this will just cause the browser to display the native HTML5 error messages. $submit_btn.click(submitBtnCheck) } function submitBtnCheck(e){ if ($myForm[0].checkValidity()) { e.preventDefault(); formSubmitCallback(); } }Johnsonjohnsonese
@Dibrin $('<input type="submit">').hide().appendTo($myForm).click().remove() doesn't work on chrome 74. Could you shed light on it?Dramamine
use .reportValidity(); to show native browser error messages without submitting the formDistributee
A
67

below code works for me,

$("#btn").click(function () {

    if ($("#frm")[0].checkValidity())
        alert('sucess');
    else
        //Validate Form
        $("#frm")[0].reportValidity()

});
Atabrine answered 24/6, 2019 at 12:39 Comment(3)
reportValidity() is the best function for highlighting required fields.Posturize
Yes, this does work like a charm, but only if the browser supports it. caniuse.com/#search=reportValidityKokanee
Why not just .reportValidity()? It will chcek validity too and return true/false.Othello
L
39

I found this solution to work for me. Just call a javascript function like this:

action="javascript:myFunction();"

Then you have the html5 validation... really simple :-)

Leavetaking answered 6/2, 2013 at 16:42 Comment(6)
This worked for me too and I think this is the best answer. I set action="javascript:0" on the <form> and bound click event on the <button> to MyFunction() and all worked great. I keep all JS out of HTML. MyFunction can then test form.checkValidity() to continue.Drysalter
Sample Code is always Helpfull.Colloquium
Binding to the form's onsubmit() is nearly always better than binding to a button's onclick(), as there are other ways to submit a form. (Notably by hitting the return key.)Amorette
+1 This is amazing. no more javascript method validation if the field is empty or if its an email. The browser can do it for us! Is this cross browser compatible?Insignificancy
Neither action="javascript:myFunction();" or action="javascript:0" works anymore in latest Firefox (67). Works on Chrome though.Earmark
For me, action="javascript:myFunction(): had to be an attribute on my HTML form element, not on a button or input element.Groundwork
M
33
    if $("form")[0].checkValidity()
      $.ajax(
        url: "url"
        type: "post"
        data: {

        }
        dataType: "json"
        success: (data) ->

      )
    else
      #important
      $("form")[0].reportValidity()

from: html5 form validation

Marketable answered 15/7, 2015 at 10:15 Comment(4)
reportValidity is only supported by Chrome 40.0Lashondra
reportValidity now is supported by Firefox since version 49Constructionist
I like this part $("form")[0].reportValidity(). I need that in case validity check is fail.Vulnerable
Great! Thank you!Guilder
B
26

Modern vanilla JS solution

Pure JavaScript has all the functions you need for this. The relevant functions are checkValidity() and reportValidity().

Test entire form

let form = document.getElementById('formId');
// Eventlistener can be another event and on another DOM object this is just an example
form.addEventListener('submit', function (event) {
    // Only needed if event is submit, otherwise this line can be skipped 
    event.preventDefault();

    // This is the important part, test if form is valid
    if (form.checkValidity() === false){
        // This is the magic function that displays the validation errors to the user
        form.reportValidity();   
        return; 
    }

    // Code if all fields are valid; continue form submit or make Ajax call.
})

Test specific field

checkValidity() and reportValidity() can not only be used on the form, but also on specific fields. No need to create a form or a dummy submit button if not needed.

// Get field of interest
let inputElement = document.querySelector("[name='" + inputName + "']");
// Check if the element is valid
if (inputElement.checkValidity() === false){
    // If not, show the errors to the user
    inputElement.reportValidity();
    return;
}

// Nothing? Great, continue to the Ajax call or whatever

This has to be in a function called by an event listener to make sense, obviously.

Bearish answered 17/2, 2022 at 12:15 Comment(2)
if you have jQuery $("#myform") then you go $("#myform")[0].checkValidity()Rubberize
This is the best answer on this page lol jQuery L - vanilla JS all the way.Discourtesy
T
18

Here is a more general way that is a bit cleaner:

Create your form like this (can be a dummy form that does nothing):

<form class="validateDontSubmit">
...

Bind all forms that you dont really want to submit:

$(document).on('submit','.validateDontSubmit',function (e) {
    //prevent the form from doing a submit
    e.preventDefault();
    return false;
})

Now lets say you have an <a> (within the <form>) that on click you want to validate the form:

$('#myLink').click(function(e){
  //Leverage the HTML5 validation w/ ajax. Have to submit to get em. Wont actually submit cuz form
  //has .validateDontSubmit class
  var $theForm = $(this).closest('form');
  //Some browsers don't implement checkValidity
  if (( typeof($theForm[0].checkValidity) == "function" ) && !$theForm[0].checkValidity()) {
     return;
  }

  //if you've gotten here - play on playa'
});

Few notes here:

  • I have noticed that you don't have to actually submit the form for validation to occur - the call to checkValidity() is enough (at least in chrome). If others could add comments with testing this theory on other browsers I'll update this answer.
  • The thing that triggers the validation does not have to be within the <form>. This was just a clean and flexible way to have a general purpose solution..
Topotype answered 27/2, 2013 at 16:38 Comment(0)
P
15

May be late to the party but yet somehow I found this question while trying to solve similar problem. As no code from this page worked for me, meanwhile I came up with solution that works as specified.

Problem is when your <form> DOM contain single <button> element, once fired, that <button> will automatically sumbit form. If you play with AJAX, You probably need to prevent default action. But there is a catch: If you just do so, You will also prevent basic HTML5 validation. Therefore, it is good call to prevent defaults on that button only if the form is valid. Otherwise, HTML5 validation will protect You from submitting. jQuery checkValidity() will help with this:

jQuery:

$(document).ready(function() {
  $('#buttonID').on('click', function(event) {
    var isvalidate = $("#formID")[0].checkValidity();
    if (isvalidate) {
      event.preventDefault();
      // HERE YOU CAN PUT YOUR AJAX CALL
    }
  });
});

Code described above will allow You to use basic HTML5 validation (with type and pattern matching) WITHOUT submitting form.

Plague answered 13/9, 2016 at 12:23 Comment(0)
D
6

You speak of two different things "HTML5 validation" and validation of HTML form using javascript/jquery.

HTML5 "has" built-in options for validating a form. Such as using "required" attribute on a field, which could (based on browser implementation) fail form submission without using javascript/jquery.

With javascrip/jquery you can do something like this

$('your_form_id').bind('submit', function() {
   // validate your form here
   return (valid) ? true : false;
});
Downstroke answered 8/8, 2012 at 14:44 Comment(4)
I want to trigger the validation without submitting the form.Meaning
As per your update - I still think this is correct solution. You didn't specify how do you want to trigger the triggerHtml5Validation() function. The above code will attach submit event to your form; on submit you intercept the event and validate the form. If you never ever want to submit the form, simply return false; and the submit will never occur.Downstroke
return (valid) ? true : false === return valid. :)Caprifig
Oops, I +1'ed @davi because I was thinking the exact same thing at first. But it's not really the same, as just return valid doesn't return false for null/undefined values. But it doesn't really matter, the answer was pseudo-code anyway, the point is: use return false to not submit the form ^^Persson
F
5
var $myForm = $('#myForm ');
if (!$myForm[0].checkValidity()) {
  $('<input type="submit">').hide().appendTo($myForm).click().remove();
}
Friedland answered 21/12, 2016 at 7:43 Comment(1)
it doesn't work on chrome 74. Could I cast light on it?Dramamine
A
3

To check all the required fields of form without using submit button you can use below function.

You have to assign required attribute to the controls.

  $("#btnSave").click(function () {
    $(":input[required]").each(function () {                     
        var myForm = $('#form1');
        if (!$myForm[0].checkValidity()) 
          {                
            $(myForm).submit();              
          }
        });
  });
Amongst answered 4/10, 2013 at 6:35 Comment(0)
O
3

You don't need jQuery to achieve this. In your form add:

onsubmit="return buttonSubmit(this)

or in JavaScript:

myform.setAttribute("onsubmit", "return buttonSubmit(this)");

In your buttonSubmit function (or whatver you call it), you can submit the form using AJAX. buttonSubmit will only get called if your form is validated in HTML5.

In case this helps anyone, here is my buttonSubmit function:

function buttonSubmit(e)
{
    var ajax;
    var formData = new FormData();
    for (i = 0; i < e.elements.length; i++)
    {
        if (e.elements[i].type == "submit")
        {
            if (submitvalue == e.elements[i].value)
            {
                submit = e.elements[i];
                submit.disabled = true;
            }
        }
        else if (e.elements[i].type == "radio")
        {
            if (e.elements[i].checked)
                formData.append(e.elements[i].name, e.elements[i].value);
        }
        else
            formData.append(e.elements[i].name, e.elements[i].value);
    }
    formData.append("javascript", "javascript");
    var action = e.action;
    status = action.split('/').reverse()[0] + "-status";
    ajax = new XMLHttpRequest();
    ajax.addEventListener("load", manageLoad, false);
    ajax.addEventListener("error", manageError, false);
    ajax.open("POST", action);
    ajax.send(formData);
    return false;
}

Some of my forms contain multiple submit buttons, hence this line if (submitvalue == e.elements[i].value). I set the value of submitvalue using a click event.

Oireachtas answered 19/3, 2016 at 20:31 Comment(0)
V
3

This way works well for me:

  1. Add onSubmit attribute in your form, don't forget to include return in the value.

    <form id='frm-contact' method='POST' action='' onSubmit="return contact()">
    
  2. Define the function.

    function contact(params) {
        $.ajax({
            url: 'sendmail.php',
            type: "POST",
            dataType: "json",
            timeout: 5000,
            data: { params:params },
            success: function (data, textStatus, jqXHR) {
                // callback
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(jqXHR.responseText);
            }
        });
    
        return false;
    }
    
Volnak answered 17/9, 2018 at 6:23 Comment(0)
I
2

I had a rather complex situation, where I needed multiple submit buttons to process different things. For example, Save and Delete.

The basis was that it was also unobtrusive, so I couldn't just make it a normal button. But also wanted to utilize html5 validation.

As well the submit event was overridden in case the user pressed enter to trigger the expected default submission; in this example save.

Here is the efforts of the processing of the form to still work with/without javascript and with html5 validation, with both submit and click events.

jsFiddle Demo - HTML5 validation with submit and click overrides

xHTML

<form>
    <input type="text" required="required" value="" placeholder="test" />
    <button type="submit" name="save">Save</button>
    <button type="submit" name="delete">Delete</button>
</form>

JavaScript

//wrap our script in an annonymous function so that it can not be affected by other scripts and does not interact with other scripts
//ensures jQuery is the only thing declared as $
(function($){
    var isValid = null;
    var form = $('form');
    var submitButton = form.find('button[type="submit"]')
    var saveButton = submitButton.filter('[name="save"]');
    var deleteButton = submitButton.filter('[name="delete"]');

    //submit form behavior
    var submitForm = function(e){
        console.log('form submit');
        //prevent form from submitting valid or invalid
        e.preventDefault();
        //user clicked and the form was not valid
        if(isValid === false){
            isValid = null;
            return false;
        }
        //user pressed enter, process as if they clicked save instead
        saveButton.trigger('click');
    };

    //override submit button behavior
    var submitClick = function(e){
        //Test form validitiy (HTML5) and store it in a global variable so both functions can use it
        isValid = form[0].checkValidity();
        if(false === isValid){
            //allow the browser's default submit event behavior 
            return true;
        }
        //prevent default behavior
        e.preventDefault();
        //additional processing - $.ajax() etc
        //.........
        alert('Success');
    };

    //override submit form event
    form.submit(submitForm);

    //override submit button click event
    submitButton.click(submitClick);
})(jQuery);

The caveat to using Javascript is that the browser's default onclick must propagate to the submit event MUST occur in order to display the error messages without supporting each browser in your code. Otherwise if the click event is overridden with event.preventDefault() or return false it will never propagate to the browser's submit event.

The thing to point out is that in some browsers will not trigger the form submit when the user presses enter, instead it will trigger the first submit button in the form. Hence there is a console.log('form submit') to show that it does not trigger.

Injector answered 10/2, 2014 at 1:5 Comment(2)
We are prolly aware that this could be done without jQuery, but OP authored title of this topic: "How to force a html5 form validation without submitting it via jQuery", explicitly suggesting jQuery have to be used.Plague
@Plague My answer uses jQuery explicitly. It differs in that it handles processing the HTML5 validation with multiple submit buttons and prevents the AJAX form submission when invalid. Defaulting to the save action when the user presses the enter key on the keyboard. Which at the time of my posting none of the provided answers was a solution for either multiple submit buttons or the capturing of the enter key to prevent ajax submission.Injector
V
2

You can do it without submitting the form.

For example, if the form submit button with id "search" is in the other form . You can call click event on that submit button and call ev.preventDefault after that. For my case I validate form B from Form A submission. Like this

function validateFormB(ev){ // DOM Event object
  //search is in Form A
  $("#search").click();
  ev.preventDefault();
  //Form B validation from here on
}
Vaillancourt answered 14/2, 2014 at 6:37 Comment(0)
L
2
$(document).on("submit", false);

submitButton.click(function(e) {
    if (form.checkValidity()) {
        form.submit();
    }
});
Leavitt answered 19/12, 2015 at 5:49 Comment(1)
$(document).on("submit", false); //this one worked perfectly, this is what i was searching for :)Krebs
B
1
$("#form").submit(function() { $("#saveButton").attr("disabled", true); });

not a best answer but works for me.

Bael answered 22/4, 2015 at 4:11 Comment(0)
D
1

I know this has already been answered, but I have another possible solution.

If using jquery, you can do this.

First create a couple of extensions on jquery so you can resuse these as needed.

$.extend({
    bypassDefaultSubmit: function (formName, newSubmitMethod) {
        $('#'+formName).submit(function (event) {
            newSubmitMethod();
            event.preventDefault();
        }
    }
});

Next do something like this where you want to use it.

<script type="text/javascript">
    /*if you want to validate the form on a submit call, 
      and you never want the form to be submitted via
      a normal submit operation, or maybe you want handle it.
    */
    $(function () {
        $.bypassDefaultSubmit('form1', submit);
    });
    function submit(){ 
        //do something, or nothing if you just want the validation
    }

</script>
Dogmatics answered 31/7, 2015 at 4:53 Comment(0)
F
1

This worked form me to display the native HTML 5 error messages with form validation.

<button id="btnRegister" class="btn btn-success btn btn-lg" type="submit"> 
 Register 
</button>


$('#RegForm').on('submit', function() 
{

  if (!this.checkValidity())
  {
    // if form is not valid show native error messages 
    return false;
  }
  else
  {
    // if form is valid, show please wait message and disable the button           
    $("#btnRegister").html("<i class='fa fa-spinner fa-spin'></i> Please Wait...");

    $(this).find(':submit').attr('disabled', 'disabled');
  }
});

Note: RegForm is the form id.

Reference

Hope helps someone.

Fablan answered 19/11, 2016 at 10:31 Comment(1)
you have to add event to enable the disabled submit buttonSpurrier
M
1

This is a pretty straight forward way of having HTML5 perform validation for any form, while still having modern JS control over the form. The only caveat is the submit button must be inside the <form>.

html

<form id="newUserForm" name="create">
Email<input type="email" name="username" id="username" size="25" required>
Phone<input type="tel" id="phone" name="phone" pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}" size="12" maxlength="12" required>
<input id="submit" type="submit" value="Create Account" >
</form>

js

// bind in ready() function
jQuery( "#submit" ).click( newAcctSubmit );

function newAcctSubmit()
{
  var myForm = jQuery( "#newUserForm" );

  // html 5 is doing the form validation for us,
  // so no need here (but backend will need to still for security)
  if ( ! myForm[0].checkValidity() )
  {
    // bonk! failed to validate, so return true which lets the
    // browser show native validation messages to the user
    return true;
  }

  // post form with jQuery or whatever you want to do with a valid form!
  var formVars = myForm.serialize();
  etc...
}
Mikes answered 14/12, 2016 at 22:40 Comment(0)
R
0

I think the best approach

will be using jQuery Validation plugin which uses best practice for form validation and it also has good browser support. So you don't need to worry about browser compatibility issues.

And we can use jQuery validation valid() function which checks whether the selected form is valid or whether all selected elements are valid without submitting the form.

<form id="myform">
   <input type="text" name="name" required>
   <br>
   <button type="button">Validate!</button>
</form>
<script>
  var form = $( "#myform" );
  form.validate();
  $( "button" ).click(function() {
    console.log( "Valid: " + form.valid() );
  });
</script>
Revival answered 29/5, 2019 at 8:2 Comment(0)
A
0

According to the question html5 validity should be validate able using jQuery at first and in most of the answer this is not happening and the reason for this is as following:

while validating using html5 form's default function

checkValidity();// returns true/false

we need to understand that jQuery returns object array, while selecting like this

$("#myForm")

therefore, you need to specify the first index to make checkValidity() function work

$('#myForm')[0].checkValidity()

here is the complete solution:

<button type="button" name="button" onclick="saveData()">Save</button>

function saveData()
{
    if($('#myForm')[0].checkValidity()){
        $.ajax({
          type: "POST",
          url: "save.php",
          data: data,
          success: function(resp){console.log("Response: "+resp);}
        });
    }
}
Antidepressant answered 3/7, 2019 at 11:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.