[html] Manually Triggering Form Validation using jQuery

I have a form with several different fieldsets. I have some jQuery that displays the field sets to the users one at a time. For browsers that support HTML5 validation, I'd love to make use of it. However, I need to do it on my terms. I'm using JQuery.

When a user clicks a JS Link to move to the next fieldset, I need the validation to happen on the current fieldset and block the user from moving forward if there is issues.

Ideally, as the user loses focus on an element, validation will occur.

Currently have novalidate going and using jQuery. Would prefer to use the native method. :)

This question is related to html jquery validation

The answer is


For input field

<input id="PrimaryPhNumber" type="text" name="mobile"  required
                                       pattern="^[789]\d{9}$" minlenght="10" maxLength="10" placeholder="Eg: 9444400000"
                                       class="inputBoxCss"/>
$('#PrimaryPhNumber').keyup(function (e) {
        console.log(e)
        let field=$(this)
        if(Number(field.val()).toString()=="NaN"){
            field.val('');
            field.focus();
            field[0].setCustomValidity('Please enter a valid phone number');
            field[0].reportValidity()
            $(":focus").css("border", "2px solid red");
        }
    })

_x000D_
_x000D_
var field = $("#field")_x000D_
field.keyup(function(ev){_x000D_
    if(field[0].value.length < 10) {_x000D_
        field[0].setCustomValidity("characters less than 10")_x000D_
        _x000D_
    }else if (field[0].value.length === 10) {_x000D_
        field[0].setCustomValidity("characters equal to 10")_x000D_
        _x000D_
    }else if (field[0].value.length > 10 && field[0].value.length < 20) {_x000D_
        field[0].setCustomValidity("characters greater than 10 and less than 20")_x000D_
        _x000D_
    }else if(field[0].validity.typeMismatch) {_x000D_
     field[0].setCustomValidity("wrong email message")_x000D_
        _x000D_
    }else {_x000D_
     field[0].setCustomValidity("") // no more errors_x000D_
        _x000D_
    }_x000D_
    field[0].reportValidity()_x000D_
    _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="email" id="field">
_x000D_
_x000D_
_x000D_


I'm not sure it's worth it for me to type this all up from scratch since this article published in A List Apart does a pretty good job explaining it. MDN also has a handy guide for HTML5 forms and validation (covering the API and also the related CSS).


In some extent, You CAN trigger HTML5 form validation and show hints to user without submitting the form!

Two button, one for validate, one for submit

Set a onclick listener on the validate button to set a global flag(say justValidate) to indicate this click is intended to check the validation of the form.

And set a onclick listener on the submit button to set the justValidate flag to false.

Then in the onsubmit handler of the form, you check the flag justValidate to decide the returning value and invoke the preventDefault() to stop the form to submit. As you know, the HTML5 form validation(and the GUI hint to user) is preformed before the onsubmit event, and even if the form is VALID you can stop the form submit by returning false or invoke preventDefault().

And, in HTML5 you have a method to check the form's validation: the form.checkValidity(), then in you can know if the form is validate or not in your code.

OK, here is the demo: http://jsbin.com/buvuku/2/edit


Html Code:

<form class="validateDontSubmit">
....
<button style="dislay:none">submit</button>
</form>
<button class="outside"></button>

javascript( using Jquery):

<script type="text/javascript">

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

$(document).ready(function(){
// using button outside trigger click
    $('.outside').click(function() {
        $('.validateDontSubmit button').trigger('click');
    });
});
</script>

Hope this will help you


Somewhat easy to make add or remove HTML5 validation to fieldsets.

 $('form').each(function(){

    // CLEAR OUT ALL THE HTML5 REQUIRED ATTRS
    $(this).find('.required').attr('required', false);

    // ADD THEM BACK TO THE CURRENT FIELDSET
    // I'M JUST USING A CLASS TO IDENTIFY REQUIRED FIELDS
    $(this).find('fieldset.current .required').attr('required', true);

    $(this).submit(function(){

        var current     = $(this).find('fieldset.current')
        var next        = $(current).next()

        // MOVE THE CURRENT MARKER
        $(current).removeClass('current');
        $(next).addClass('current');

        // ADD THE REQUIRED TAGS TO THE NEXT PART
        // NO NEED TO REMOVE THE OLD ONES
        // SINCE THEY SHOULD BE FILLED OUT CORRECTLY
        $(next).find('.required').attr('required', true);

    });

});

TL;DR: Not caring about old browsers? Use form.reportValidity().

Need legacy browser support? Read on.


It actually is possible to trigger validation manually.

I'll use plain JavaScript in my answer to improve reusability, no jQuery is needed.


Assume the following HTML form:

<form>
  <input required>
  <button type="button">Trigger validation</button>
</form>

And let's grab our UI elements in JavaScript:

var form = document.querySelector('form')
var triggerButton = document.querySelector('button')

Don't need support for legacy browsers like Internet Explorer? This is for you.

All modern browsers support the reportValidity() method on form elements.

triggerButton.onclick = function () {
    form.reportValidity()
}

That's it, we're done. Also, here's a simple CodePen using this approach.


Approach for older browsers

Below is a detailed explanation how reportValidity() can be emulated in older browsers.

However, you don't need to copy&paste those code blocks into your project yourself — there is a ponyfill/polyfill readily available for you.

Where reportValidity() is not supported, we need to trick the browser a little bit. So, what will we do?

  1. Check validity of the form by calling form.checkValidity(). This will tell us if the form is valid, but not show the validation UI.
  2. If the form is invalid, we create a temporary submit button and trigger a click on it. Since the form is not valid, we know it won't actually submit, however, it will show validation hints to the user. We'll remove the temporary submit button immedtiately, so it will never be visible to the user.
  3. If the form is valid, we don't need to interfere at all and let the user proceed.

In code:

triggerButton.onclick = function () {
  // Form is invalid!
  if (!form.checkValidity()) {
    // Create the temporary button, click and remove it
    var tmpSubmit = document.createElement('button')
    form.appendChild(tmpSubmit)
    tmpSubmit.click()
    form.removeChild(tmpSubmit)

  } else {
    // Form is valid, let the user proceed or do whatever we need to
  }
}

This code will work in pretty much any common browser (I've tested it successfully down to IE11).

Here's a working CodePen example.


I seem to find the trick: Just remove the form target attribute, then use a submit button to validate the form and show hints, check if form valid via JavaScript, and then post whatever. The following code works for me:

<form>
  <input name="foo" required>
  <button id="submit">Submit</button>
</form>

<script>
$('#submit').click( function(e){
  var isValid = true;
  $('form input').map(function() {
    isValid &= this.validity['valid'] ;
  }) ;
  if (isValid) {
    console.log('valid!');
    // post something..
  } else
    console.log('not valid!');
});
</script>

Another way to resolve this problem:

$('input').oninvalid(function (event, errorMessage) {
    event.target.focus();
});

When there is a very complex (especially asynchronous) validation process, there is a simple workaround:

<form id="form1">
<input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" />
<input type="submit" id="form1_submit_hidden" style="display:none" />
</form>
...
<script>
function submitIfVeryComplexValidationIsOk() {
    var form1 = document.forms['form1']
    if (!form1.checkValidity()) {
        $("#form1_submit_hidden").click()
        return
    }

    if (checkForVeryComplexValidation() === 'Ok') {
         form1.submit()
    } else {
         alert('form is invalid')
    }
}
</script>

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery