387

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?

2

8 Answers 8

408

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.

5
  • 23
    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". Apr 24, 2009 at 22:15
  • 38
    Leaving it out would mean that the method would always be applied, even when the element isn't required. Apr 27, 2009 at 16:34
  • I take it that this.optional(element) returns true if element is null?
    – tnunamak
    Jan 2, 2011 at 18:40
  • 13
    for it to run, "amount" should be the id and name of some element in the page? Feb 9, 2011 at 10:41
  • 7
    Yes, amount refers to the name attribute of some input form field. Feb 10, 2011 at 19:15
105
$(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"
            }
        }
    });
});
10
  • 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.. May 25, 2010 at 15:33
  • 1
    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 May 27, 2010 at 9:19
  • 25
    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
    Apr 21, 2012 at 11:29
  • 1
    @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. Mar 19, 2013 at 17:57
  • 2
    there is a remote method for jquery validate: jqueryvalidation.org/remote-method
    – TecHunter
    Sep 22, 2014 at 8:23
73
// 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 }    
});
2
  • 8
    addClassRules is a nice addition to the answer.
    – Four
    May 10, 2011 at 18:51
  • unclear documentation links: Rules and Error Messages
    – mangupt
    Oct 4, 2022 at 14:08
56

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>

3
  • 2
    only for jquery.validate ver >= 1.10 Nov 16, 2017 at 8:42
  • 1
    I couldn't for the life of me find this in the official documentation, I wish they made this more clear. Thanks!
    – Josh Mc
    May 25, 2020 at 0:18
  • unclear documentation links: Rules and Error Messages
    – mangupt
    Oct 4, 2022 at 14:08
22

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");
0
20

You can add a custom rule like this:

$.validator.addMethod(
    'booleanRequired',
    function (value, element, requiredValue) {
        return value === requiredValue;
    },
    'Please check your input.'
);

And add it as a rule like this:

PhoneToggle: {
    booleanRequired: 'on'
}        
2

For this case: user signup form, user must choose a username that is not taken.

This means we have to create a customized validation rule, which will send async http request with remote server.

  1. create a input element in your html:
<input name="user_name" type="text" >
  1. declare your form validation rules:
  $("form").validate({
    rules: {
      'user_name': {
        //  here jquery validate will start a GET request, to 
        //  /interface/users/is_username_valid?user_name=<input_value>
        //  the response should be "raw text", with content "true" or "false" only
        remote: '/interface/users/is_username_valid'
      },
    },
  1. the remote code should be like:
class Interface::UsersController < ActionController::Base
  def is_username_valid
    render :text => !User.exists?(:user_name => params[:user_name])
  end
end
-1

Step 1 Included the cdn like

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

     <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

Step 2 Code Like

  $(document).ready(function(){
        $("#submit").click(function () {
              $('#myform').validate({ // initialize the plugin
                rules: {
                    id: {
                        required: true,
                        email: true
                    },
                    password: {
                        required: true,
                        minlength: 1
                    }
                },
                messages: {
                    id: {
                        required: "Enter Email Id"

                    },
                    password: {
                        required: "Enter Email Password"

                    }
                },
                submitHandler: function (form) { // for demo
                    alert('valid form submitted'); // for demo
                    return false; // for demo
                }
            });
       }):
  }); 
1
  • Where's the custom rule?
    – LarryBud
    Oct 1 at 14:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.