ソースを参照

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

phuoc 11 年 前
コミット
9b856d22f7

+ 2 - 0
CHANGELOG.md

@@ -49,10 +49,12 @@ __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/) adds 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)
 * [#456](https://github.com/nghuuphuoc/bootstrapvalidator/issues/456): Adjust the feedback icon position for ```.input-group``` element
+* [#465](https://github.com/nghuuphuoc/bootstrapvalidator/issues/465): Support dynamic message
 
 __Bug Fixes__
 * [#288](https://github.com/nghuuphuoc/bootstrapvalidator/issues/288): Fix [date validator](http://bootstrapvalidator.com/validators/date/) issue on IE8

+ 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-03 9:37:21 AM
+ * @version     v0.5.0-dev, built on 2014-07-05 5:51:14 PM
  * @author      https://twitter.com/nghuuphuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @license     MIT

+ 31 - 12
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-03 9:37:21 AM
+ * @version     v0.5.0-dev, built on 2014-07-05 5:51:14 PM
  * @author      https://twitter.com/nghuuphuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @license     MIT
@@ -742,7 +742,7 @@
                     validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
 
                     // validateResult can be a $.Deferred object ...
-                    if ('object' === typeof validateResult) {
+                    if ('object' === typeof validateResult && validateResult.resolve) {
                         this.updateStatus(updateAll ? field : $field, this.STATUS_VALIDATING, validatorName);
                         $field.data('bv.dfs.' + validatorName, validateResult);
 
@@ -761,6 +761,11 @@
                             }
                         });
                     }
+                    // ... or object { valid: true/false, message: 'dynamic message' }
+                    else if ('object' === typeof validateResult && validateResult.valid !== undefined && validateResult.message !== undefined) {
+                        this.updateMessage(updateAll ? field : $field, validatorName, validateResult.message);
+                        this.updateStatus(updateAll ? field : $field, validateResult.valid ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
+                    }
                     // ... or a boolean value
                     else if ('boolean' === typeof validateResult) {
                         this.updateStatus(updateAll ? field : $field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
@@ -2467,13 +2472,7 @@
 ;(function($) {
     $.fn.bootstrapValidator.i18n.greaterThan = $.extend($.fn.bootstrapValidator.i18n.greaterThan || {}, {
         'default': 'Please enter a value greater than or equal to %s',
-        notInclusive: 'Please enter a value greater than %s',
-
-        getMessage: function(options) {
-            return (options.inclusive === true || options.inclusive === undefined)
-                    ? $.fn.bootstrapValidator.helpers.format(this['default'], options.value)
-                    : $.fn.bootstrapValidator.helpers.format(this.notInclusive, options.value);
-        }
+        notInclusive: 'Please enter a value greater than %s'
     });
 
     $.fn.bootstrapValidator.validators.greaterThan = {
@@ -2500,18 +2499,38 @@
          * @param {BootstrapValidator} validator Validate plugin instance
          * @param {jQuery} $field Field element
          * @param {Object} options Can consist of the following keys:
-         * - value: The number used to compare to
+         * - value: Define the number to compare with. It 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();
             if (value === '') {
                 return true;
             }
+
+            var compareTo = options.value;
+            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]);
+                }
+            }
+
             value = parseFloat(value);
-			return (options.inclusive === true || options.inclusive === undefined) ? (value >= options.value) : (value > options.value);
+			return (options.inclusive === true || options.inclusive === undefined)
+                    ? { valid: value >= compareTo, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan['default'],   compareTo) }
+                    : { valid: value > compareTo,  message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan.notInclusive, compareTo) };
         }
     };
 }(window.jQuery));

ファイルの差分が大きいため隠しています
+ 4 - 4
dist/js/bootstrapValidator.min.js


+ 24 - 10
src/js/validator/greaterThan.js

@@ -1,13 +1,7 @@
 (function($) {
     $.fn.bootstrapValidator.i18n.greaterThan = $.extend($.fn.bootstrapValidator.i18n.greaterThan || {}, {
         'default': 'Please enter a value greater than or equal to %s',
-        notInclusive: 'Please enter a value greater than %s',
-
-        getMessage: function(options) {
-            return (options.inclusive === true || options.inclusive === undefined)
-                    ? $.fn.bootstrapValidator.helpers.format(this['default'], options.value)
-                    : $.fn.bootstrapValidator.helpers.format(this.notInclusive, options.value);
-        }
+        notInclusive: 'Please enter a value greater than %s'
     });
 
     $.fn.bootstrapValidator.validators.greaterThan = {
@@ -34,18 +28,38 @@
          * @param {BootstrapValidator} validator Validate plugin instance
          * @param {jQuery} $field Field element
          * @param {Object} options Can consist of the following keys:
-         * - value: The number used to compare to
+         * - value: Define the number to compare with. It 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();
             if (value === '') {
                 return true;
             }
+
+            var compareTo = options.value;
+            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]);
+                }
+            }
+
             value = parseFloat(value);
-			return (options.inclusive === true || options.inclusive === undefined) ? (value >= options.value) : (value > options.value);
+			return (options.inclusive === true || options.inclusive === undefined)
+                    ? { valid: value >= compareTo, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan['default'],   compareTo) }
+                    : { valid: value > compareTo,  message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan.notInclusive, compareTo) };
         }
     };
 }(window.jQuery));

+ 112 - 0
test/spec.js

@@ -1639,6 +1639,118 @@ describe('ean', function() {
     });
 });
 
+function greaterThanCompare() {
+    var compareTo = $('#greaterThanForm').find('[name="minAge"]').val();
+    $('#msg').html('greaterThanCompare() called; compare to ' + compareTo);
+    return compareTo;
+};
+
+TestSuite = $.extend({}, TestSuite, {
+    greaterThan: {
+        compareTo: function(value, validator, $field) {
+            var compareTo = $('#greaterThanForm').find('[name="minAge"]').val();
+            $('#msg').html('TestSuite.greaterThan.compareTo() called; compare to ' + compareTo);
+            return compareTo;
+        }
+    }
+});
+
+describe('greaterThan', function() {
+    beforeEach(function() {
+        $([
+            '<form class="form-horizontal" id="greaterThanForm">',
+                '<div id="msg"></div>',
+                '<div class="form-group">',
+                    '<input type="text" name="minAge" />',
+                '</div>',
+                '<div class="form-group">',
+                    '<input type="text" name="age" data-bv-greaterthan data-bv-greaterthan-value="18" />',
+                '</div>',
+            '</form>'
+        ].join('\n')).appendTo('body');
+
+        $('#greaterThanForm').bootstrapValidator();
+
+        this.bv      = $('#greaterThanForm').data('bootstrapValidator');
+        this.$minAge = this.bv.getFieldElements('minAge');
+        this.$age    = this.bv.getFieldElements('age');
+    });
+
+    afterEach(function() {
+        $('#greaterThanForm').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(20);
+        this.bv.validate();
+        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();
+        this.bv = $('#greaterThanForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(10);
+        this.$age.val(20);
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        this.bv.resetForm();
+        this.$minAge.val(20);
+        this.$age.val(10);
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'greaterThan')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan['default'], this.$minAge.val()));
+    });
+
+    it('compare to return value of a function', function() {
+        this.$age.attr('data-bv-greaterthan-value', 'greaterThanCompare');
+        this.bv.destroy();
+        this.bv = $('#greaterThanForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(20);
+        this.$age.val(18);
+        this.bv.validate();
+        expect($('#msg').html()).toEqual('greaterThanCompare() called; compare to 20');
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'greaterThan')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan['default'], this.$minAge.val()));
+
+        this.bv.resetForm();
+        this.$minAge.val(18);
+        this.$age.val(20);
+        this.bv.validate();
+        expect($('#msg').html()).toEqual('greaterThanCompare() called; compare to 18');
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+
+    it('compare to return value of a namespace function', function() {
+        this.$age.attr('data-bv-greaterthan-value', 'TestSuite.greaterThan.compareTo');
+        this.bv.destroy();
+        this.bv = $('#greaterThanForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(20);
+        this.$age.val(18);
+        this.bv.validate();
+        expect($('#msg').html()).toEqual('TestSuite.greaterThan.compareTo() called; compare to 20');
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'greaterThan')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan['default'], this.$minAge.val()));
+
+        this.bv.resetForm();
+        this.$minAge.val(18);
+        this.$age.val(20);
+        this.bv.validate();
+        expect($('#msg').html()).toEqual('TestSuite.greaterThan.compareTo() called; compare to 18');
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+});
+
 describe('iban', function() {
     beforeEach(function() {
         var html = [

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

@@ -0,0 +1,111 @@
+function greaterThanCompare() {
+    var compareTo = $('#greaterThanForm').find('[name="minAge"]').val();
+    $('#msg').html('greaterThanCompare() called; compare to ' + compareTo);
+    return compareTo;
+};
+
+TestSuite = $.extend({}, TestSuite, {
+    greaterThan: {
+        compareTo: function(value, validator, $field) {
+            var compareTo = $('#greaterThanForm').find('[name="minAge"]').val();
+            $('#msg').html('TestSuite.greaterThan.compareTo() called; compare to ' + compareTo);
+            return compareTo;
+        }
+    }
+});
+
+describe('greaterThan', function() {
+    beforeEach(function() {
+        $([
+            '<form class="form-horizontal" id="greaterThanForm">',
+                '<div id="msg"></div>',
+                '<div class="form-group">',
+                    '<input type="text" name="minAge" />',
+                '</div>',
+                '<div class="form-group">',
+                    '<input type="text" name="age" data-bv-greaterthan data-bv-greaterthan-value="18" />',
+                '</div>',
+            '</form>'
+        ].join('\n')).appendTo('body');
+
+        $('#greaterThanForm').bootstrapValidator();
+
+        this.bv      = $('#greaterThanForm').data('bootstrapValidator');
+        this.$minAge = this.bv.getFieldElements('minAge');
+        this.$age    = this.bv.getFieldElements('age');
+    });
+
+    afterEach(function() {
+        $('#greaterThanForm').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(20);
+        this.bv.validate();
+        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();
+        this.bv = $('#greaterThanForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(10);
+        this.$age.val(20);
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        this.bv.resetForm();
+        this.$minAge.val(20);
+        this.$age.val(10);
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'greaterThan')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan['default'], this.$minAge.val()));
+    });
+
+    it('compare to return value of a function', function() {
+        this.$age.attr('data-bv-greaterthan-value', 'greaterThanCompare');
+        this.bv.destroy();
+        this.bv = $('#greaterThanForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(20);
+        this.$age.val(18);
+        this.bv.validate();
+        expect($('#msg').html()).toEqual('greaterThanCompare() called; compare to 20');
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'greaterThan')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan['default'], this.$minAge.val()));
+
+        this.bv.resetForm();
+        this.$minAge.val(18);
+        this.$age.val(20);
+        this.bv.validate();
+        expect($('#msg').html()).toEqual('greaterThanCompare() called; compare to 18');
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+
+    it('compare to return value of a namespace function', function() {
+        this.$age.attr('data-bv-greaterthan-value', 'TestSuite.greaterThan.compareTo');
+        this.bv.destroy();
+        this.bv = $('#greaterThanForm').bootstrapValidator().data('bootstrapValidator');
+
+        this.$minAge.val(20);
+        this.$age.val(18);
+        this.bv.validate();
+        expect($('#msg').html()).toEqual('TestSuite.greaterThan.compareTo() called; compare to 20');
+        expect(this.bv.isValid()).toEqual(false);
+        expect(this.bv.getMessages('age', 'greaterThan')[0]).toEqual($.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.greaterThan['default'], this.$minAge.val()));
+
+        this.bv.resetForm();
+        this.$minAge.val(18);
+        this.$age.val(20);
+        this.bv.validate();
+        expect($('#msg').html()).toEqual('TestSuite.greaterThan.compareTo() called; compare to 18');
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+});