116

I have a form with a couple of buttons and I'm using jQuery Validation Plugin from http://jquery.bassistance.de/validate/. I just want to know if there is any way I can check if the form is considered in valid state by jquery validation plugin from anywhere in my javascript code.

Jaime Hablutzel
  • 6,117
  • 5
  • 40
  • 57
  • 5
    For those wishing to use HTML5 and vanilla JS (no jQuery): http://stackoverflow.com/questions/12470622/how-can-i-check-the-validity-of-an-html5-form-that-does-not-contain-a-submit-but – 2540625 Sep 11 '16 at 20:20
  • 1
    ```document.forms['formID'].reportValidity()``` returns true if all the form elements validity is true. (For non jQuery users) – Sathvik Mar 19 '21 at 17:02

8 Answers8

179

Use .valid() from the jQuery Validation plugin:

$("#form_id").valid();

Checks whether the selected form is valid or whether all selected elements are valid. validate() needs to be called on the form before checking it using this method.

Where the form with id='form_id' is a form that has already had .validate() called on it.

Ian Dunn
  • 3,541
  • 6
  • 26
  • 44
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • Thank you, I was already doing something like: $j("#myform label.error").each( function(i,e) { if($j(e).css('display') != 'none') { existErrors = true ; } }); :S Thanks – Jaime Hablutzel Jul 12 '11 at 03:13
  • There's actually no need to have .validate() run on the form first. You can simply do if (form.valid()) {} and that will work, where 'form' is the form element you're targeting. – Gareth Daine Oct 23 '14 at 10:50
  • awesome.. i was stuck with fileupload and finally found a way through this post... waah Taaj :) – Gags Aug 18 '15 at 18:16
  • The `$("#form_id").valid()` method always returns true :-( regardless of the validity of the form. It only triggers the validity check, but returns true, even when the form is invalid. – Supreme Dolphin Aug 21 '18 at 12:06
  • 16
    TypeError: $("#myForm").valid() is not a function. – artgrohe Oct 26 '18 at 09:15
  • had the same issue with @artgrohe – Teoman Tıngır Oct 19 '19 at 08:42
  • 6
    If you are receiving a `TypeError valid() not a function` add the plugin to your file since its a plugin not included in jquery library eg. `` – StackEdd Jan 15 '20 at 14:50
35

2015 answer: we have this out of the box on modern browsers, just use the HTML5 CheckValidity API from jQuery. I've also made a jquery-html5-validity module to do this:

npm install jquery-html5-validity

Then:

var $ = require('jquery')
require("jquery-html5-validity")($);

then you can run:

$('.some-class').isValid()

true
Community
  • 1
  • 1
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
34

@mikemaccana answer is useful.

And I also used https://github.com/ryanseddon/H5F. Found on http://microjs.com. It's some kind of polyfill and you can use it as follows (jQuery is used in example):

if ( $('form')[0].checkValidity() ) {
    // the form is valid
}
gorodezkiy
  • 3,299
  • 2
  • 34
  • 42
7

For a group of inputs you can use an improved version based in @mikemaccana's answer

$.fn.isValid = function(){
    var validate = true;
    this.each(function(){
        if(this.checkValidity()==false){
            validate = false;
        }
    });
};

now you can use this to verify if the form is valid:

if(!$(".form-control").isValid){
    return;
}

You could use the same technique to get all the error messages:

$.fn.getVelidationMessage = function(){
    var message = "";
    var name = "";
    this.each(function(){
        if(this.checkValidity()==false){
            name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
            message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n<br>";
        }
    })
    return message;
}
Matias Medina
  • 133
  • 1
  • 8
6

valid() method.

http://docs.jquery.com/Plugins/Validation/valid

ysrb
  • 6,693
  • 2
  • 29
  • 30
4

iContribute: It's never too late for a right answer.

var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
  form.submit();
}else{
  console.log("Required field missing.");
}

This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.

  • Note, that `:input`and `:visible` selectors are jQuery extensions and not part of CSS. See details in [docs](https://api.jquery.com/input-selector/) – Geradlus_RU Aug 24 '17 at 21:19
  • 3
    A form can also be invalid because of pattern matching and not only because missing required fields – frank Sep 10 '17 at 19:55
1

For Magento, you check validation of form by something like below.

You can try this:

require(["jquery"], function ($) {
    $(document).ready(function () {
        $('#my-button-name').click(function () { // The button type should be "button" and not submit
            if ($('#form-name').valid()) {
                alert("Validation pass");
                return false;
            }else{
                alert("Validation failed");
                return false;
            }
        });
    });
});

Hope this may help you!

Kazim Noorani
  • 263
  • 3
  • 6
0

In case you're validating before submitting the form:

$(function(){
    $('.needs-validation').on('submit', function(event){
        if(!event.target.checkValidity()){
            // Form didn't pass validation
            event.preventDefault();
            $(this).addClass('was-validated');
        }
    })
})

You can't use $('form')[0].checkValidity() with multiple forms in the view.

Edmund Sulzanok
  • 1,883
  • 3
  • 20
  • 39