简体   繁体   中英

How to add a Custom EqualTo To rule in jQuery.validation

I had a problem getting the sum of 2 inputs to be equal to a dynamic value. In my case I needed, 2 fields to be equal to 100. I thought I'd post my solution below for anyone else who may need this as is or to make a new custom validation rule.

Below is the answer I got. Field1 and Field2 must be equal to 100 in the below answer.

$(document).ready(function(){
var msg;
var dynamicErrorMsg = function () { return msg; }

jQuery.validator.addMethod("equalToValue", function(value, element, param) {
    var target = parseInt($( param[0] ).val());
    var total = parseInt(value) + target;
    msg = " Field 1 and 2 must be equal to " + param[1];
    return this.optional(element) || (total == param[1]);
}, dynamicErrorMsg);

$("form").validate({
    rules: {
         field1: {
             equalToValue: ["#field2", 100]
         }
    }
});
});

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