views:

13154

answers:

5

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 lease one of a group of checkboxes is checked?

+18  A: 

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.

Mark Spangler
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".
machineghost
Leaving it out would mean that the method would always be applied, even when the element isn't required.
Mark Spangler
+3  A: 

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;
}, "* Check at least one checkbox");
A: 

Hi edward, I need this functionality as well, but my code isn't executing... Can you post a more complete example of you code?

I don't know where to write the $.validator.addMethod, should that be outside of the form.validate code?

I currently have:

jQuery.validator.addMethod("at_least_one_cat_selected", function(value, element) { var the_list_array = $("ul#list_all_categories li input:checked"); return the_list_array.length > 0; }, "Please specify the correct domain for your documents");

and then inside the validation call:

rules: { list_all_categories: {at_least_one_cat_selected: true} },

but that isn't working. Please note: list_all_categories is the name of the that contains all checkboxes?

+5  A: 
$(document).ready(function(){
$.validator.addMethod("uniqueUserName", function(value, element) {
      $.ajax({
          type: "POST",
           url: "http://"+location.host+"/checkUser.php",
          data: "checkUsername="+value,
          dataType:"html",
       success: function(msg)
       {
          // if the user exists, it returns a string "true"
          if(msg == "true")
             return false;  // already exists
          return true;      // username is free to use
       }
     })
}, "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 cheractors",
       uniqueUserName: "This Username is taken already"
      }
    }
 }); 
Tracy
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..
Mikelangelo
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
Mikelangelo
@Mikelangelo: Can you show us what you mean by "added a variable before the addMethod"? I'm lost on that line and I'm having the same issues that you did. Thanks in advance!
Loony2nz
A: 
########################
## In validation Rules #
########################
regemail: {
    required: true,
    email: true,
    remote: {
        url: "checkmail.php"
    }
},

#####################
## In message Rules #
#####################
regemail: {
    required: "Email is required",
    email: "Invalid Format",
    remote: ""
}

###########################
## Modify Jquery Validate #
###########################
#Search For:
var valid = response === true;
if ( valid ) {

#Change To:
var valid = response.data;
if ( !valid ) {
   valid = true;

#Search For
} else {
   var errors = {};

#Change To
} else {
   valid = false;
   var errors = {};


#Search For:
errors[element.id] = previous.message = response || validator.defaultMessage( element, "remote" );

#Change To:
errors[element.id] = response.data || validator.defaultMessage( element, "remote" );

#PHP Returns JSON return ($m == $m) ? false : 'Email Already Registered'

Shawn Rebeblo