jQuery Validate Plugin - How to create a simple custom rule?

jquery validation custom rule function
jquery validate add rule
jquery validate add custom rule dynamically
jquery validate rules list
jquery custom form validation
jquery validate custom rule regex
jquery custom validation without plugin
jquery validation custom email rule

How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod) that doesn't use a regex?

For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?

You can create a simple rule by doing something like this:

jQuery.validator.addMethod("greaterThanZero", function(value, element) {
    return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");

And then applying this like so:

$('validatorElement').validate({
    rules : {
        amount : { greaterThanZero : true }
    }
});

Just change the contents of the 'addMethod' to validate your checkboxes.

jQuery.validator.addMethod(), Hello: I am having trouble getting adding custom rules to JQuery form validation to work properly. I want to use the default rules to make input required, custom rule to JQuery Validate. in Using jQuery Plugins • 7 years ago. You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true"; So to check if at least one of a group of checkboxes is checked:

$(document).ready(function(){
    var response;
    $.validator.addMethod(
        "uniqueUserName", 
        function(value, element) {
            $.ajax({
                type: "POST",
                url: "http://"+location.host+"/checkUser.php",
                data: "checkUsername="+value,
                dataType:"html",
                success: function(msg)
                {
                    //If username exists, set response to true
                    response = ( msg == 'true' ) ? true : false;
                }
             });
            return response;
        },
        "Username is Already Taken"
    );

    $("#regFormPart1").validate({
        username: {
            required: true,
            minlength: 8,
            uniqueUserName: true
        },
        messages: {
            username: {
                required: "Username is required",
                minlength: "Username must be at least 8 characters",
                uniqueUserName: "This Username is taken already"
            }
        }
    });
});

Adding custom rule to JQuery Validate, This post shows you how to add a custom validation rule to your forms using the jQuery.validate.js plugin. This post supports the Setup form� You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true"; So to check if at least one of a group of checkboxes is checked:

// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
        return jQuery.validator.methods['date'].call(
            this,value,element
        )||value==("0000/00/00");
    }, "Please enter a valid date."
);

// connect it to a css class
jQuery.validator.addClassRules({
    optdate : { optdate : true }    
});

jQuery Custom Validation Rule - fieldPresent, Jquery validation plugin api provides the flexibility to add custom In below example I have added "validateCity" custom validation rule method� This post shows you how to add a custom validation rule to your forms using the jQuery.validate.js plugin. This post supports the Setup form validation using jQuery in just 2 minutes post. I used

Custom Rule and data attribute

You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true";

So to check if at least one of a group of checkboxes is checked:

data-rule-oneormorechecked

<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" />

addMethod

$.validator.addMethod("oneormorechecked", function(value, element) {
   return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");

And you can also override the message of a rule (ie: Atleast 1 must be selected) by using the syntax data-msg-rulename="my new message".

NOTE

If you use the data-rule-rulename method then you will need to make sure the rule name is all lowercase. This is because the jQuery validation function dataRules applies .toLowerCase() to compare and the HTML5 spec does not allow uppercase.

Working Example

$.validator.addMethod("oneormorechecked", function(value, element) {
  return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");

$('.validate').validate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>

<form class="validate">
    red<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" data-msg-oneormorechecked="Check one or more!" /><br/>
    blue<input type="checkbox" name="colours[]" value="blue" /><br/>
    green<input type="checkbox" name="colours[]" value="green" /><br/>
    <input type="submit" value="submit"/>
</form>

How to Define Custom Jquery Validation Method Example Or Jquery , The jQuery Validation plugin; Adding validation rules; In this chapter, you'll see how to define custom validation rules that check entered text against expected� The.validate () documentation is a good guide, here's the blurb about.rules ("add", option): Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $ ("form").validate () is called first.

Thanks, it worked!

Here's the final code:

$.validator.addMethod("greaterThanZero", function(value, element) {
    var the_list_array = $("#some_form .super_item:checked");
    return the_list_array.length > 0;
}, "* Please check at least one check box");

Chapter 14. Creating validation rules, How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod ) that doesn't use a regex? For example, what function would create� You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true"; So to check if at least one of a group of checkboxes is checked:

jQuery Validate Plugin, In this screen-cast, I will show you how to get up and running with the awesome jQuery Duration: 7:27 Posted: May 4, 2015 Key/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an object consisting of rule/parameter pairs or a plain String. Can be combined with class/attribute/data rules. Each rule can be specified as having a depends-property to apply the rule only in certain conditions.

jQuery Validation Plugin: Custom Validation (2/4), In this lecture we'll learn how to create custom validation methods using the jQuery Validation Duration: 5:10 Posted: Jul 4, 2014 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 to setup validation for a form.

jQuery Validation custom validation methods, In this tutorial, I will explain you about Validation jQuery Plugin, using that you can define Rules; Example; Some Built-in methods; Create custom method; Conclusion Creating a basic form and adding validation to it.

Comments
  • 95 upvotes, I guess this mean bassistance.de/jquery-plugins/jquery-plugin-validation documentation might be unclear :P
  • Don't know if you are still searching (4 years later) but this could help learn.jquery.com/plugins/…
  • What is the this.optional(element) || doing in that function? It seems like every rule has that, but I can't tell why it would be relevant for any rule except "required".
  • Leaving it out would mean that the method would always be applied, even when the element isn't required.
  • I take it that this.optional(element) returns true if element is null?
  • for it to run, "amount" should be the id and name of some element in the page?
  • Yes, amount refers to the name attribute of some input form field.
  • I tried this method and it works pretty good, however, men returning any other msg than true it still doesnt validate "ok" it is stuck in "Username is Already Taken", what can be wrong? i have also checked that it is returned properly by echoing values instead of returning false and true, and this works. seems to me that my browser is not picking up the return false , return true? this is making me crazy..
  • got it to work by inserting a variable that is called result before the addmethod, seems the true, false values are registering properly within the success function
  • Be careful with this. This is not fully functional code in that the AJAX "success" is going to come back after 'return response;' runs, resulting in unexpected behaviors
  • @Malachi is correct. This can be fixed by doing a sync call instead but that's nasty. I wonder if there's some other way of achieving this? There is remote as others have suggested but as far as I can tell that only allows one validation, so it wouldn't work if you need to to two async validations or have several error messages depending on the response.
  • there is a remote method for jquery validate: jqueryvalidation.org/remote-method
  • addClassRules is a nice addition to the answer.