Browse Source

#430: between adds support for comparing to other field, return value of a callback function

phuoc 11 years ago
parent
commit
08a8ff1354

+ 1 - 1
CHANGELOG.md

@@ -49,7 +49,7 @@ __Improvements__
 * [#420](https://github.com/nghuuphuoc/bootstrapvalidator/issues/420): Enable/disable particular validator
 * [#422](https://github.com/nghuuphuoc/bootstrapvalidator/issues/422): Exclude particular field by ```excluded``` option or ```data-bv-excluded``` attribute
 * [#426](https://github.com/nghuuphuoc/bootstrapvalidator/issues/426): Add test suite
-* [#430](https://github.com/nghuuphuoc/bootstrapvalidator/issues/430): [greaterThan](http://bootstrapvalidator.com/validators/greaterThan/), [lessThan](http://bootstrapvalidator.com/validators/lessThan/) add support for comparing to other field, return value of a callback function
+* [#430](https://github.com/nghuuphuoc/bootstrapvalidator/issues/430): [between](http://bootstrapvalidator.com/validators/between/), [greaterThan](http://bootstrapvalidator.com/validators/greaterThan/), [lessThan](http://bootstrapvalidator.com/validators/lessThan/) add support for comparing to other field, return value of a callback function
 * [#431](https://github.com/nghuuphuoc/bootstrapvalidator/issues/431): Add built time to the build file
 * [#432](https://github.com/nghuuphuoc/bootstrapvalidator/issues/432): Define the callback via ```data-bv-callback-callback``` attribute
 * [#447](https://github.com/nghuuphuoc/bootstrapvalidator/pull/447): [zipCode validator](http://bootstrapvalidator.com/validators/zipCode/) allow to set the country code via another field or callback, thanks to [@AlaskanShade](https://github.com/AlaskanShade)

+ 1 - 1
dist/css/bootstrapValidator.min.css

@@ -2,7 +2,7 @@
  * BootstrapValidator (http://bootstrapvalidator.com)
  * The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3
  *
- * @version     v0.5.0-dev, built on 2014-07-05 6:00:00 PM
+ * @version     v0.5.0-dev, built on 2014-07-05 6:42:43 PM
  * @author      https://twitter.com/nghuuphuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @license     MIT

+ 30 - 11
dist/js/bootstrapValidator.js

@@ -2,7 +2,7 @@
  * BootstrapValidator (http://bootstrapvalidator.com)
  * The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3
  *
- * @version     v0.5.0-dev, built on 2014-07-05 6:00:00 PM
+ * @version     v0.5.0-dev, built on 2014-07-05 6:42:43 PM
  * @author      https://twitter.com/nghuuphuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @license     MIT
@@ -1731,13 +1731,7 @@
 ;(function($) {
     $.fn.bootstrapValidator.i18n.between = $.extend($.fn.bootstrapValidator.i18n.between || {}, {
         'default': 'Please enter a value between %s and %s',
-        notInclusive: 'Please enter a value between %s and %s strictly',
-
-        getMessage: function(options) {
-            return (options.inclusive === true || options.inclusive === undefined)
-                    ? $.fn.bootstrapValidator.helpers.format(this['default'], [options.min, options.max])
-                    : $.fn.bootstrapValidator.helpers.format(this.notInclusive, [options.min, options.max]);
-        }
+        notInclusive: 'Please enter a value between %s and %s strictly'
     });
 
     $.fn.bootstrapValidator.validators.between = {
@@ -1767,9 +1761,16 @@
          * @param {Object} options Can consist of the following keys:
          * - min
          * - max
+         *
+         * The min, max keys define the number which the field value compares to. min, max can be
+         *      - A number
+         *      - Name of field which its value defines the number
+         *      - Name of callback function that returns the number
+         *      - A callback function that returns the number
+         *
          * - inclusive [optional]: Can be true or false. Default is true
          * - message: The invalid message
-         * @returns {Boolean}
+         * @returns {Object}
          */
         validate: function(validator, $field, options) {
             var value = $field.val();
@@ -1777,10 +1778,28 @@
                 return true;
             }
 
+            var determineValue = function(compareTo) {
+                if ('function' === typeof compareTo) {
+                    compareTo = $.fn.bootstrapValidator.helpers.call(compareTo, [value, validator, $field]);
+                } else if ('string' === typeof compareTo && !$.isNumeric(compareTo)) {
+                    var $compareField = validator.getFieldElements(compareTo);
+                    if ($compareField.length) {
+                        compareTo = $compareField.val();
+                    } else {
+                        compareTo = $.fn.bootstrapValidator.helpers.call(compareTo, [value, validator, $field]);
+                    }
+                }
+
+                return compareTo;
+            };
+
+            var min = determineValue(options.min),
+                max = determineValue(options.max);
+
             value = parseFloat(value);
 			return (options.inclusive === true || options.inclusive === undefined)
-				    ? (value >= options.min && value <= options.max)
-				    : (value > options.min && value < options.max);
+                    ? { valid: value >= min && value <= max, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between['default'],   [min, max]) }
+                    : { valid: value > min  && value <  max, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between.notInclusive, [min, max]) };
         }
     };
 }(window.jQuery));

File diff suppressed because it is too large
+ 3 - 3
dist/js/bootstrapValidator.min.js


+ 29 - 10
src/js/validator/between.js

@@ -1,13 +1,7 @@
 (function($) {
     $.fn.bootstrapValidator.i18n.between = $.extend($.fn.bootstrapValidator.i18n.between || {}, {
         'default': 'Please enter a value between %s and %s',
-        notInclusive: 'Please enter a value between %s and %s strictly',
-
-        getMessage: function(options) {
-            return (options.inclusive === true || options.inclusive === undefined)
-                    ? $.fn.bootstrapValidator.helpers.format(this['default'], [options.min, options.max])
-                    : $.fn.bootstrapValidator.helpers.format(this.notInclusive, [options.min, options.max]);
-        }
+        notInclusive: 'Please enter a value between %s and %s strictly'
     });
 
     $.fn.bootstrapValidator.validators.between = {
@@ -37,9 +31,16 @@
          * @param {Object} options Can consist of the following keys:
          * - min
          * - max
+         *
+         * The min, max keys define the number which the field value compares to. min, max can be
+         *      - A number
+         *      - Name of field which its value defines the number
+         *      - Name of callback function that returns the number
+         *      - A callback function that returns the number
+         *
          * - inclusive [optional]: Can be true or false. Default is true
          * - message: The invalid message
-         * @returns {Boolean}
+         * @returns {Object}
          */
         validate: function(validator, $field, options) {
             var value = $field.val();
@@ -47,10 +48,28 @@
                 return true;
             }
 
+            var determineValue = function(compareTo) {
+                if ('function' === typeof compareTo) {
+                    compareTo = $.fn.bootstrapValidator.helpers.call(compareTo, [value, validator, $field]);
+                } else if ('string' === typeof compareTo && !$.isNumeric(compareTo)) {
+                    var $compareField = validator.getFieldElements(compareTo);
+                    if ($compareField.length) {
+                        compareTo = $compareField.val();
+                    } else {
+                        compareTo = $.fn.bootstrapValidator.helpers.call(compareTo, [value, validator, $field]);
+                    }
+                }
+
+                return compareTo;
+            };
+
+            var min = determineValue(options.min),
+                max = determineValue(options.max);
+
             value = parseFloat(value);
 			return (options.inclusive === true || options.inclusive === undefined)
-				    ? (value >= options.min && value <= options.max)
-				    : (value > options.min && value < options.max);
+                    ? { valid: value >= min && value <= max, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between['default'],   [min, max]) }
+                    : { valid: value > min  && value <  max, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between.notInclusive, [min, max]) };
         }
     };
 }(window.jQuery));

+ 146 - 2
test/spec.js

@@ -1393,6 +1393,152 @@ describe('message', function() {
     });
 });
 
+function betweenCompareMin() {
+    var compareTo = $('#betweenForm').find('[name="minAge"]').val();
+    $('#msgMin').html('betweenCompareMin() called; compare to ' + compareTo);
+    return compareTo;
+};
+
+function betweenCompareMax() {
+    var compareTo = $('#betweenForm').find('[name="maxAge"]').val();
+    $('#msgMax').html('betweenCompareMax() called; compare to ' + compareTo);
+    return compareTo;
+};
+
+TestSuite = $.extend({}, TestSuite, {
+    between: {
+        compareToMin: function(value, validator, $field) {
+            var compareTo = $('#betweenForm').find('[name="minAge"]').val();
+            $('#msgMin').html('TestSuite.between.compareToMin() called; compare to ' + compareTo);
+            return compareTo;
+        },
+
+        compareToMax: function(value, validator, $field) {
+            var compareTo = $('#betweenForm').find('[name="maxAge"]').val();
+            $('#msgMax').html('TestSuite.between.compareToMax() called; compare to ' + compareTo);
+            return compareTo;
+        }
+    }
+});
+
+describe('between', function() {
+    beforeEach(function() {
+        $([
+            '<form class="form-horizontal" id="betweenForm">',
+                '<div id="msgMin"></div>',
+                '<div id="msgMax"></div>',
+                '<div class="form-group">',
+                    '<input type="text" name="minAge" />',
+                '</div>',
+                '<div class="form-group">',
+                    '<input type="text" name="maxAge" />',
+                '</div>',
+                '<div class="form-group">',
+                    '<input type="text" name="age" data-bv-between data-bv-between-min="18" data-bv-between-max="100" />',
+                '</div>',
+            '</form>'
+        ].join('\n')).appendTo('body');
+
+        $('#betweenForm').bootstrapValidator();
+
+        this.bv      = $('#betweenForm').data('bootstrapValidator');
+        this.$minAge = this.bv.getFieldElements('minAge');
+        this.$maxAge = this.bv.getFieldElements('maxAge');
+        this.$age    = this.bv.getFieldElements('age');
+    });
+
+    afterEach(function() {
+        $('#betweenForm').bootstrapValidator('destroy').remove();
+    });
+
+    it('compare to value', function() {
+        this.$age.val(10);
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+
+        this.bv.resetForm();
+        this.$age.val(120);
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+
+        this.bv.resetForm();
+        this.$age.val(30);
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+
+    it('compare to other field', function() {
+        this.$age.attr('data-bv-between-min', 'minAge')
+                 .attr('data-bv-between-max', 'maxAge');
+        this.bv.destroy();
+        this.bv = $('#betweenForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(2);
+        this.$maxAge.val(10);
+        this.$age.val(5);
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        this.bv.resetForm();
+        this.$minAge.val(20);
+        this.$maxAge.val(40);
+        this.$age.val(50);
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'between')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between['default'], [this.$minAge.val(), this.$maxAge.val()]));
+    });
+
+    it('compare to return value of a function', function() {
+        this.$age.attr('data-bv-between-min', 'betweenCompareMin')
+                 .attr('data-bv-between-max', 'betweenCompareMax');
+        this.bv.destroy();
+        this.bv = $('#betweenForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(20);
+        this.$maxAge.val(30);
+        this.$age.val(18);
+        this.bv.validate();
+        expect($('#msgMin').html()).toEqual('betweenCompareMin() called; compare to 20');
+        expect($('#msgMax').html()).toEqual('betweenCompareMax() called; compare to 30');
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'between')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between['default'], [this.$minAge.val(), this.$maxAge.val()]));
+
+        this.bv.resetForm();
+        this.$minAge.val(2);
+        this.$maxAge.val(10);
+        this.$age.val(6);
+        this.bv.validate();
+        expect($('#msgMin').html()).toEqual('betweenCompareMin() called; compare to 2');
+        expect($('#msgMax').html()).toEqual('betweenCompareMax() called; compare to 10');
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+
+    it('compare to return value of a namespace function', function() {
+        this.$age.attr('data-bv-between-min', 'TestSuite.between.compareToMin')
+                 .attr('data-bv-between-max', 'TestSuite.between.compareToMax');
+        this.bv.destroy();
+        this.bv = $('#betweenForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(20);
+        this.$maxAge.val(30);
+        this.$age.val(40);
+        this.bv.validate();
+        expect($('#msgMin').html()).toEqual('TestSuite.between.compareToMin() called; compare to 20');
+        expect($('#msgMax').html()).toEqual('TestSuite.between.compareToMax() called; compare to 30');
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'between')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between['default'], [this.$minAge.val(), this.$maxAge.val()]));
+
+        this.bv.resetForm();
+        this.$minAge.val(2);
+        this.$maxAge.val(10);
+        this.$age.val(5);
+        this.bv.validate();
+        expect($('#msgMin').html()).toEqual('TestSuite.between.compareToMin() called; compare to 2');
+        expect($('#msgMax').html()).toEqual('TestSuite.between.compareToMax() called; compare to 10');
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+});
+
 function validateCaptcha(value, validator, $field) {
     var items = $('#captchaOperation').html().split(' '), sum = parseInt(items[0]) + parseInt(items[2]);
     return value === sum + '';
@@ -1694,7 +1840,6 @@ describe('greaterThan', function() {
         expect(this.bv.isValid()).toBeTruthy();
     });
 
-    // Compare to minAge field
     it('compare to other field', function() {
         this.$age.attr('data-bv-greaterthan-value', 'minAge');
         this.bv.destroy();
@@ -2955,7 +3100,6 @@ describe('lessThan', function() {
         expect(this.bv.isValid()).toBeTruthy();
     });
 
-    // Compare to maxAge field
     it('compare to other field', function() {
         this.$age.attr('data-bv-lessthan-value', 'maxAge');
         this.bv.destroy();

+ 145 - 0
test/spec/validator/between.js

@@ -0,0 +1,145 @@
+function betweenCompareMin() {
+    var compareTo = $('#betweenForm').find('[name="minAge"]').val();
+    $('#msgMin').html('betweenCompareMin() called; compare to ' + compareTo);
+    return compareTo;
+};
+
+function betweenCompareMax() {
+    var compareTo = $('#betweenForm').find('[name="maxAge"]').val();
+    $('#msgMax').html('betweenCompareMax() called; compare to ' + compareTo);
+    return compareTo;
+};
+
+TestSuite = $.extend({}, TestSuite, {
+    between: {
+        compareToMin: function(value, validator, $field) {
+            var compareTo = $('#betweenForm').find('[name="minAge"]').val();
+            $('#msgMin').html('TestSuite.between.compareToMin() called; compare to ' + compareTo);
+            return compareTo;
+        },
+
+        compareToMax: function(value, validator, $field) {
+            var compareTo = $('#betweenForm').find('[name="maxAge"]').val();
+            $('#msgMax').html('TestSuite.between.compareToMax() called; compare to ' + compareTo);
+            return compareTo;
+        }
+    }
+});
+
+describe('between', function() {
+    beforeEach(function() {
+        $([
+            '<form class="form-horizontal" id="betweenForm">',
+                '<div id="msgMin"></div>',
+                '<div id="msgMax"></div>',
+                '<div class="form-group">',
+                    '<input type="text" name="minAge" />',
+                '</div>',
+                '<div class="form-group">',
+                    '<input type="text" name="maxAge" />',
+                '</div>',
+                '<div class="form-group">',
+                    '<input type="text" name="age" data-bv-between data-bv-between-min="18" data-bv-between-max="100" />',
+                '</div>',
+            '</form>'
+        ].join('\n')).appendTo('body');
+
+        $('#betweenForm').bootstrapValidator();
+
+        this.bv      = $('#betweenForm').data('bootstrapValidator');
+        this.$minAge = this.bv.getFieldElements('minAge');
+        this.$maxAge = this.bv.getFieldElements('maxAge');
+        this.$age    = this.bv.getFieldElements('age');
+    });
+
+    afterEach(function() {
+        $('#betweenForm').bootstrapValidator('destroy').remove();
+    });
+
+    it('compare to value', function() {
+        this.$age.val(10);
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+
+        this.bv.resetForm();
+        this.$age.val(120);
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+
+        this.bv.resetForm();
+        this.$age.val(30);
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+
+    it('compare to other field', function() {
+        this.$age.attr('data-bv-between-min', 'minAge')
+                 .attr('data-bv-between-max', 'maxAge');
+        this.bv.destroy();
+        this.bv = $('#betweenForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(2);
+        this.$maxAge.val(10);
+        this.$age.val(5);
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        this.bv.resetForm();
+        this.$minAge.val(20);
+        this.$maxAge.val(40);
+        this.$age.val(50);
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'between')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between['default'], [this.$minAge.val(), this.$maxAge.val()]));
+    });
+
+    it('compare to return value of a function', function() {
+        this.$age.attr('data-bv-between-min', 'betweenCompareMin')
+                 .attr('data-bv-between-max', 'betweenCompareMax');
+        this.bv.destroy();
+        this.bv = $('#betweenForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(20);
+        this.$maxAge.val(30);
+        this.$age.val(18);
+        this.bv.validate();
+        expect($('#msgMin').html()).toEqual('betweenCompareMin() called; compare to 20');
+        expect($('#msgMax').html()).toEqual('betweenCompareMax() called; compare to 30');
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'between')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between['default'], [this.$minAge.val(), this.$maxAge.val()]));
+
+        this.bv.resetForm();
+        this.$minAge.val(2);
+        this.$maxAge.val(10);
+        this.$age.val(6);
+        this.bv.validate();
+        expect($('#msgMin').html()).toEqual('betweenCompareMin() called; compare to 2');
+        expect($('#msgMax').html()).toEqual('betweenCompareMax() called; compare to 10');
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+
+    it('compare to return value of a namespace function', function() {
+        this.$age.attr('data-bv-between-min', 'TestSuite.between.compareToMin')
+                 .attr('data-bv-between-max', 'TestSuite.between.compareToMax');
+        this.bv.destroy();
+        this.bv = $('#betweenForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(20);
+        this.$maxAge.val(30);
+        this.$age.val(40);
+        this.bv.validate();
+        expect($('#msgMin').html()).toEqual('TestSuite.between.compareToMin() called; compare to 20');
+        expect($('#msgMax').html()).toEqual('TestSuite.between.compareToMax() called; compare to 30');
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'between')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.between['default'], [this.$minAge.val(), this.$maxAge.val()]));
+
+        this.bv.resetForm();
+        this.$minAge.val(2);
+        this.$maxAge.val(10);
+        this.$age.val(5);
+        this.bv.validate();
+        expect($('#msgMin').html()).toEqual('TestSuite.between.compareToMin() called; compare to 2');
+        expect($('#msgMax').html()).toEqual('TestSuite.between.compareToMax() called; compare to 10');
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+});

+ 0 - 1
test/spec/validator/greaterThan.js

@@ -50,7 +50,6 @@ describe('greaterThan', function() {
         expect(this.bv.isValid()).toBeTruthy();
     });
 
-    // Compare to minAge field
     it('compare to other field', function() {
         this.$age.attr('data-bv-greaterthan-value', 'minAge');
         this.bv.destroy();

+ 0 - 1
test/spec/validator/lessThan.js

@@ -50,7 +50,6 @@ describe('lessThan', function() {
         expect(this.bv.isValid()).toBeTruthy();
     });
 
-    // Compare to maxAge field
     it('compare to other field', function() {
         this.$age.attr('data-bv-lessthan-value', 'maxAge');
         this.bv.destroy();