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

JavascriptJqueryJquery Validate

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

$(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"
            }
        }
    });
});

Solution 3 - Javascript

// 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 }	
});

Solution 4 - Javascript

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>

Solution 5 - Javascript

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

Solution 6 - Javascript

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'
}        

Solution 7 - Javascript

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

Solution 8 - Javascript

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
                }
            });
       }):
  }); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdwardView Question on Stackoverflow
Solution 1 - JavascriptMark SpanglerView Answer on Stackoverflow
Solution 2 - JavascriptTracyView Answer on Stackoverflow
Solution 3 - JavascriptcommonpikeView Answer on Stackoverflow
Solution 4 - JavascriptBenGView Answer on Stackoverflow
Solution 5 - JavascriptedwardView Answer on Stackoverflow
Solution 6 - JavascriptBogdan MatesView Answer on Stackoverflow
Solution 7 - JavascriptSiweiView Answer on Stackoverflow
Solution 8 - JavascriptDevang HireView Answer on Stackoverflow