简体   繁体   中英

JQuery validation plugin and custom rule

I'm using the jquery.validation plugin in my web app. I have this general code for form validation:

$('form[data-toggle="validator"]').each(function () {
            $(this).validate({
                errorClass: "help-block error",
                errorElement: "div",
                focusCleanup: false,
                focusInvalid: false,
                submitHandler: function(form){
                    $("[type=submit]",form).prop("disabled",true);
                    form.submit();
                }
            });
         });

When I need the validation I just set the data-toggle attribute to the form.

In a particular case I would like to add a custom rule, not for a single input element, but for all the form. I would like to add it at runtime, is it possibile?

I think you are searching for method to add a custom validation method. Below is the example where I add a validation to check for max length for a value at runtime.

jQuery.validator.addMethod("maxLengthName", function(value, element) {
  return value.length>30;
}, 'Please enter a name with length less than 30.');

value :- the current value of the validated element
element :- the element to be validated

Update

The above way is to add a custom method for a single input element. Now the question remains how can we do same for form and not just 1 input element.

No, we cannot add a custom rule to the <form> element

But there is a way you can add a single rule for multiple inputs. Below is the example for same. In this example we check if addition of Input 1 and Input 2 is equal to Total entered by user

<form id="TotalForm" name="TotalForm">
    <label>Input 1</label>
    <input type="text" name="inputone" id="inputone" class="required" />
    <label>Input 2</label>
    <input type="text" name="inputTwo" id="inputTwo" class="required" />
    <label>Total</label>
    <input type="text" name="inputTotal" id="inputTotal" class="required totalMatch" />
</form>


jQuery.validator.addMethod("totalMatch",function(value) {
        total = parseFloat($('#inputone').val()) + parseFloat($('#inputTwo').val());
        return total == parseFloat($('#inputTotal').val());
    }, "Total is not matching with Input 1 and  Input 2!");

    jQuery.validator.classRuleSettings.totalMatch = { totalMatch: true };

Now you can call validate on document.ready function like below and

$("#TotalForm").validate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM