Firstly, and most importantly, you must wrap your input elements inside <form></form> tags for the jQuery Validate plugin to operate. However, a submit button is not required.

Secondly, you can programatically trigger the validity test of any or all elements without a submit button by using the .valid() method.

Copy$(document).ready(function() {

    $('#myform').validate({  // initialize the plugin on your form.
        // rules, options, and/or callback functions
    });

    // trigger validity test of any element using the .valid() method.
    $('#myelement').valid();

    // trigger validity test of the entire form using the .valid() method.
    $('#myform').valid();

    // the .valid() method also returns a boolean...
    if ($('#myform').valid()) {
        // something to do if form is valid
    }

});

DEMO: http://jsfiddle.net/URQGG/

Answer from Sparky on Stack Overflow
๐ŸŒ
Jqueryvalidation
jqueryvalidation.org โ€บ documentation
Documentation | jQuery Validation Plugin
A single line of jQuery to select the form and apply the validation plugin, plus a few annotations on each element to specify the validation rules. Of course that isn't the only way to specify rules. You also don't have to rely on those default messages, but they come in handy when starting ...
๐ŸŒ
Formden
formden.com โ€บ blog โ€บ validate-contact-form-jquery
How to Validate Form Fields Using jQuery | Formden.com
March 19, 2014 - You can also download this demo ... entered. Valid inputs will turn green while invalid inputs will turn red. When the submit button is pushed, jQuery will check whether all fields are valid....
Discussions

javascript - jQuery Validation for all inputs of a given type - Stack Overflow
I'm trying to write a JavaScript function that would cover the validation of all the input elements of the type="time". I am looking at the documentation of jQuery Validate but I'm only finding exa... More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Validate form input fields using jquery - Stack Overflow
I'm working on form validation. Everything is working fine what I actually want is I want to add some more input fields like checkbox, radio button, select and textarea, upload file and like so int... More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Validate all the inputs of a table in jquery - Stack Overflow
I have a set of inputs that are dynamically generated and their id's incremented based on the number of items in an array More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Validate an input field of a form in Jquery - Stack Overflow
you could tag your required fields with a specific class and iterate trough the fields which have this class 'required', this makes it easy to change your decision which fields you want to check ยท i suggest the jQuery validation plugin from http://bassistance.de/jquery-plugins/jquery-plug... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ form-validation-using-jquery
Form Validation using jQuery | GeeksforGeeks
September 16, 2024 - Perform the validation task for all the input fields such as username, email, password, and confirm password. Example 1: This example illustrates the simple form validation using jQuery.
๐ŸŒ
Jqueryvalidation
jqueryvalidation.org โ€บ reference
Reference documentation | jQuery Validation Plugin
For example, if you're writing a custom method for validating email addresses inside a single field, you could call the existing email method for each email: An error message displays a hint for the user about invalid elements, and what is wrong. There are four ways to provide error messages. Via the title attribute of the input element to validate, via data attributes, via error labels and via plugin settings (option messages). All validation rules included here provide a default error message which you can use for prototyping, because it is used when no specific message is provided.
๐ŸŒ
SitePoint
sitepoint.com โ€บ blog โ€บ javascript โ€บ how to set up basic jquery form validation in two minutes
jQuery Form Validation Tutorial: Simple Example with jQuery Validation Plugin | SitePoint
January 6, 2025 - The plugin allows you to customize error messages for specific validation rules. You can define custom error messages in the validation settings for each input field. Yes, you can perform form data validation using custom jQuery code without relying on the Validation plugin. You need to write JavaScript functions that manually check form inputs and display error messages.
Top answer
1 of 2
11

Here is the working code:

https://jsfiddle.net/bhumi/o2gxgz9r/47570/

I have changed selector to use id

You need to use loop in handle error:

var Validator = function(form) {

    this.form = $(form);

    var Elements = {
        name: {
            selector: $('input[type=text]'),
            reg: /^[a-zA-Z]{2,20}$/
        },

        email: {
            selector: $('input[type=email]'),
            reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i
        },

        message: {
            selector: $('textarea'),
            reg: /^\s+$/
        }
    };

    var handleError = function(element, message, v1) {
        if (v1.selector.length > 1) {
            var ss = v1.selector;

            $(ss).each(function(i, v) {
            $(v).removeClass('input-error');
            if($(v).val() == ''){
              $(v).addClass('input-error');
              var $err_msg = $(v).parent('div');
              if($(v).parent('div').find('.error').length == 0) {
                    var error = $('<div class="error"></div>').text(message);
               }else{
                    $(v).parent('div').find('.error').text('');
                    var error = $(v).parent('div').find('.error').text(message);
                    $(this).siblings('.error').show();
               }
               error.appendTo($err_msg);
             }else{
               $(v).siblings('.error').text('')
             }
             $(v).keyup(function() {
                 $(error).fadeOut(1000, function() {
                     element.removeClass('input-error');
                });
             });
          });
        } else {
            element.addClass('input-error');
            var $err_msg = element.parent('div');
            if(element.parent('div').find('.error').length == 0) {
                  var error = $('<div class="error"></div>').text(message);
             }else{
                  element.parent('div').find('.error').text('');
                  var error = element.parent('div').find('.error').text(message);
                  $(this).siblings('.error').show();
             }
            error.appendTo($err_msg);
            element.keyup(function() {
                $(error).fadeOut(1000, function() {
                    element.removeClass('input-error');
                });
            });
        }

    };

    this.validate = function() {

        this.form.submit(function(e) {

            for (var i in Elements) {

                var type = i;
                var validation = Elements[i];
                switch (type) {
                    case 'name':
                        if (!validation.reg.test(validation.selector.val())) {
                            handleError(validation.selector, 'Not a valid name.', validation);
                        }
                        break;
                    case 'email':
                        if (!validation.reg.test(validation.selector.val())) {
                            handleError(validation.selector, 'Not a valid e-mail address.', validation);
                        }
                        break;
                    case 'message':
                        if (validation.reg.test(validation.selector.val()) || validation.selector.val() == '') {
                        handleError(validation.selector, 'Message field cannot be empty.', validation);
                        }
                        break;
                    default:
                        break;


                }

            }

            e.preventDefault();
        });

    };
};

var validator = new Validator('#test');
validator.validate();
2 of 2
1

I hope this is what you were trying to achieve. This took longer than expected but I tried to achieve it. This whole form is custom form. You could have used the existing plugins to achieve it. Any which ways it took much time to figure it out. Consider the question as most of things are working, ignore if something's not what you want.

$(document).ready(function() {

  /* contact form validation */
  var Validator = function(formObject) {
    this.form = $(formObject);
    var Elements = {
      name: {
        reg: /^[a-zA-Z ]{2,20}$/,
        require: true,
        error: "Not a valid name.",
      },

      email: {
        reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
        error: "Not a valid e-mail address.",
      },
      phone: {
        reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
        error: "Not a valid number.",
      },

      message: {
        reg: /^(?!\s*$).+/,
        error: "Message field cannot be empty.",
      },
      gender: {
        error: "gender is required",
      },
      selectOption: {
        error: "this field is required",
        required: true
      }
    };

    var handleError = function(element, message) {
      element.addClass('input-error');
      var $err_msg = element.parent('div');
      $err_msg.find('.error').remove();

      var error = $('<div class="error"></div>').text(message);
      error.appendTo($err_msg);
      console.log(element);


      element.on('keypress change', function() {
        $(error).fadeOut(1000, function() {
          console.log(element);
          element.removeClass('input-error');
        });
      });

    };

    /* Select Option */

    this.validate = function() {
      var errorCount = 0;

      this.form.find("select").each(function(index, field) {
        var type = $(field).data("validation");
        var validation = Elements[type];
        if ($(field).val() == "") {
          errorCount++;
          handleError($(field), validation.error);
        }
      });

      this.form.find("input, textarea").each(function(index, field) {
        var type = $(field).data("validation");
        var validation = Elements[type];
        if (validation !== undefined) {
          var re = new RegExp(validation.reg);
          if (validation) {
            if (!re.test($(field).val())) {
              errorCount++;
              handleError($(field), validation.error);
            }
          }
        }
      })

      /* Radio button */

      var radioList = $('input:radio');
      var radioNameList = new Array();
      var radioUniqueNameList = new Array();
      var notCompleted = 0;
      for (var i = 0; i < radioList.length; i++) {
        radioNameList.push(radioList[i].name);
      }
      radioUniqueNameList = jQuery.unique(radioNameList);
      console.log(radioUniqueNameList);
      for (var i = 0; i < radioUniqueNameList.length; i++) {
        var field = $('#' + radioUniqueNameList[i]);
        var type = field.data("validation");
        var validation = Elements[type];
        if ($('input[name=' + type + ']:checked', '#test').val() == undefined) {
          errorCount++;
          handleError($(field), validation.error);
        }
      }

      return errorCount == 0;
    };
  };

  /* Submit form*/

  $(function() {

    $("form#test").on('submit', function(e) {
      var NoErrors = new Validator(this).validate();
      if (NoErrors == true) {
        $.ajax({
          url: this.action,
          type: this.method,
          data: $(this).serialize(),
          success: function() {
            // AJAX request finished, handle the results and error msg
            $('.success_msg').fadeIn().delay(3000).fadeOut();
            $('input[type!="submit"], textarea').val('').removeClass('error');
          }
        });

      }
      return false;
    })

  })

});
body {
  background: #fff;
  color: #333;
  font: 76% Verdana, sans-serif;
}

form {
  margin: 1em 0 0 2em;
  width: 90%;
}

fieldset {
  margin: 0;
  border: 1px solid #ccc;
  padding-bottom: 1em;
}

legend {
  font-weight: bold;
  text-transform: uppercase;
}

label {
  float: left;
  width: 5em;
  padding-right: 2em;
  font-weight: bold;
}

div {
  margin-bottom: 30px;
}

input {
  font: 1em Verdana, sans-serif;
}

fieldset ul li input {
  float: left;
  width: 120px;
  border: 1px solid #ccc;
}

textarea {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  font: 1em Verdana, sans-serif;
}

form p {
  margin: 0;
  padding: 0.4em 0 0 7em;
}

form p input {
  background: #666;
  color: #fff;
  font-weight: bold;
}

div.error {
  clear: left;
  margin-left: 5.3em;
  color: red;
  padding-right: 1.3em;
  height: 100%;
  padding-bottom: 0.3em;
  line-height: 1.3;
}

.input-error {
  background: #ff9;
  border: 1px solid red;
}

.success_msg {
  width: 350px;
  line-height: 40px;
  border: 1px solid green;
  border-radius: 5px;
  background-color: rgba(213, 255, 187, 0.7);
  display: none;
  position: absolute;
  bottom: 5px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="test">
  <fieldset>

    <legend>Contact information</legend>


    <div>
      <label for="firstname">Firstname:</label>
      <input type="text" name="firstname" id="firstname" data-validation="name" />
    </div>


    <div>
      <label for="lastname">Lastname:</label>
      <input type="text" name="lastname" id="lastname" data-validation="name" />
    </div>

    <div>
      <label for="email">Email:</label>
      <input type="email" name="email" id="email" data-validation="email" />

    </div>
    <div>
      <label for="phone">phone</label>
      <input type="number" name="phone" id="phone" data-validation="phone" />
    </div>

    <div>
      <label>Gender:</label>
      <input type="radio" name="gender" value="male" data-validation="gender" />
      <input type="radio" name="gender" value="female" data-validation="gender">
    </div>

    <select data-validation="selectOption">
      <option value="">Select any option</option>
      <option value="red">Red</option>
      <option value="blue">Blue</option>
      <option value="green">Green</option>
    </select>

    <div>
      <label for="message">Message:</label>
      <textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
    </div>

    <p><input type="submit" name="send" id="send" value="Send" /></p>

  </fieldset>
  <div class="success_msg">
    <p>Form submitted Successfully</p>
  </div>
</form>

Find elsewhere
๐ŸŒ
Developer Diary
varunver.wordpress.com โ€บ 2014 โ€บ 03 โ€บ 07 โ€บ jquery-validate-all-inputs-within-a-div-incomplete
jQuery โ€“ Validate all inputs within a DIV (Incomplete)
March 7, 2014 - //-- Gets called on form submit function validateForm() { var arr_evalFieldNames = ["eval|company", "eval|first_name", "eval|last_name", "eval|email"]; if (!validateMandatoryElements(arr_evalFieldNames)) { return false; } } //-- Accept array of field names and return false if either one of them is blank function validateMandatoryElements(arr_fieldNames) { for (index = 0; index < arr_fieldNames.length; ++index) { $element = $( '[name="'+arr_fieldNames[index]+'"]' ); if ($element.val().trim() == "") { alert("Enter valid valid value for Eval data"); $element.focus(); return false; } } return true; }
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 39484786 โ€บ validate-all-the-inputs-of-a-table-in-jquery
javascript - Validate all the inputs of a table in jquery - Stack Overflow
This will allow you to validate the fields which are empty, and try to use the filter, that helps you to do it without any loop. ... $('#sender_container').on('submit',function(e) { e.preventDefault(); validate(); }); function validate() { $('#sender_container > input[type="text"]') .removeClass('error') .filter(function() { // Remove error classes. Filter return !$.trim(this.value); }) .addClass('error'); } ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="post" id="sender_container"> <input type="text" name="name[]" /> <input type="text" name="name[]" /> <input type="text" name="name[]" /> <input type="text" name="name[]" /> <input type="text" name="name[]" /> <input type="submit" name="submit" /> </form>
๐ŸŒ
Jqueryvalidation
jqueryvalidation.org โ€บ validate
.validate() | jQuery Validation Plugin
May 23, 2013 - Key/value pairs, where the key refers to the name of an input field, values the message to be displayed for that input. ... An array for all currently validated elements. Contains objects with the following two properties: ... The message to be displayed for an input. ... The DOMElement for this entry. errorPlacement (default: Places the error label after the invalid element) ... Customize placement of created error labels. First argument: The created error label as a jQuery object.
๐ŸŒ
The Web Fosters
thewebfosters.com โ€บ home โ€บ blogs โ€บ how to validate dynamically generated input fields with jquery validation plugin ??
How to validate dynamically generated input fields with jQuery Validation plugin ?? - The Web Fosters
May 28, 2017 - As we know jQuery validation plugin is the most commonly used client side form validation library which provides plenty of customization with an ease to save time for manually validating each HTML form elements from scratch. Though this plugin provides lots of inbuilt function to customize ...
๐ŸŒ
HTML Form Guide
html.form.guide โ€บ jquery โ€บ validation-using-jquery-examples
Form Validation Using Jquery Examples | HTML Form Guide
In the previous example, we wrote code that validated the forms data from scratch. To make this process faster and easier, you can use a library like the jQuery Validation Plugin. With this, you only have to specify a few rules for each field of your form that is to be validated, and the plugin ...
๐ŸŒ
SoloDev
solodev.com โ€บ blog โ€บ web-design โ€บ how-to-use-jquery-validator-for-your-form-validation.stml
How to Use jQuery Validator for Your Form Validation
October 14, 2019 - In this tutorial, we are using ... work. In our markup, all we need to do is add an id to our form tag and all the input fields we have such as "first name", "last name", ......
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ how-to-validate-all-input-fields-at-once
Validating all input fields simultaneously: A comprehensive guide - Javascript
May 7, 2023 - Upon encountering an empty input, trigger an error message adjacent to it to ensure that all fields display an error simultaneously. ... Instead of reinventing the wheel, I recommend utilizing a JavaScript validation plugin that will achieve precisely what you desire. This particular jQuery validation plugin is by far the most popular one.