Browse Source

#420: Enable/disable particular validator

phuoc 11 years ago
parent
commit
654d3b8924

+ 1 - 0
CHANGELOG.md

@@ -45,6 +45,7 @@ __Improvements__
 * [#382](https://github.com/nghuuphuoc/bootstrapvalidator/issues/382): Add JSHint to Grunt build
 * [#388](https://github.com/nghuuphuoc/bootstrapvalidator/issues/388): Allow to override the default options. Useful for using multiple forms in the same page
 * [#393](https://github.com/nghuuphuoc/bootstrapvalidator/pull/393): The [remote validator](http://bootstrapvalidator.com/validators/remote/) adds support for dynamic ```url``` and method type (GET/POST), thanks to [@ericnakagawa](https://github.com/ericnakagawa)
+* [#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
 * [#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

+ 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-06-29 9:01:15 AM
+ * @version     v0.5.0-dev, built on 2014-06-29 9:46:23 PM
  * @author      https://twitter.com/nghuuphuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @license     MIT

+ 35 - 8
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-06-29 9:01:15 AM
+ * @version     v0.5.0-dev, built on 2014-06-29 9:46:23 PM
  * @author      https://twitter.com/nghuuphuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @license     MIT
@@ -593,6 +593,10 @@
             counter[this.STATUS_VALID]         = 0;
 
             for (var v in validators) {
+                if (validators[v].enabled === false) {
+                    continue;
+                }
+
                 numValidators++;
                 var result = $field.data('bv.result.' + v);
                 if (result) {
@@ -733,7 +737,7 @@
 
                     // Don't validate field if it is already done
                     var result = $field.data('bv.result.' + validatorName);
-                    if (result === this.STATUS_VALID || result === this.STATUS_INVALID) {
+                    if (result === this.STATUS_VALID || result === this.STATUS_INVALID || validators[validatorName].enabled === false) {
                         this._onFieldValidated($field, validatorName);
                         continue;
                     }
@@ -995,6 +999,10 @@
                 }
 
                 for (validatorName in this.options.fields[field].validators) {
+                    if (this.options.fields[field].validators[validatorName].enabled === false) {
+                        continue;
+                    }
+
                     status = $field.data('bv.result.' + validatorName);
                     if (status !== this.STATUS_VALID) {
                         return false;
@@ -1027,8 +1035,10 @@
                 if ($f.data('bv.messages')
                       .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]')
                       .filter(function() {
-                          var v = $(this).attr('data-bv-validator');
-                          return ($f.data('bv.result.' + v) && $f.data('bv.result.' + v) !== that.STATUS_VALID);
+                          var v = $(this).attr('data-bv-validator'),
+                              f = $(this).attr('data-bv-for');
+                          return (that.options.fields[f].validators[v].enabled !== false
+                                && $f.data('bv.result.' + v) && $f.data('bv.result.' + v) !== that.STATUS_VALID);
                       })
                       .length !== 0)
                 {
@@ -1056,6 +1066,7 @@
                     .val(this.$submitButton.val())
                     .appendTo(this.$form);
             }
+
             // Submit form
             this.$form.off('submit.bv').submit();
         },
@@ -1119,7 +1130,9 @@
                         .data('bv.messages')
                         .find('.help-block[data-bv-for="' + $(this).attr('data-bv-field') + '"][data-bv-result="' + that.STATUS_INVALID + '"]' + filter)
                         .map(function() {
-                            return $(this).html();
+                            var v = $(this).attr('data-bv-validator'),
+                                f = $(this).attr('data-bv-for');
+                            return (that.options.fields[f].validators[v].enabled === false) ? '' : $(this).html();
                         })
                         .get()
                 );
@@ -1307,12 +1320,26 @@
          *
          * @param {String} field The field name
          * @param {Boolean} enabled Enable/Disable field validators
+         * @param {String} [validatorName] The validator name. If null, all validators will be enabled/disabled
          * @returns {BootstrapValidator}
          */
-        enableFieldValidators: function(field, enabled) {
-            if (this.options.fields[field].enabled !== enabled) {
+        enableFieldValidators: function(field, enabled, validatorName) {
+            var validators = this.options.fields[field].validators;
+
+            // Enable/disable particular validator
+            if (validatorName
+                && validators
+                && validators[validatorName] && validators[validatorName].enabled !== enabled)
+            {
+                this.options.fields[field].validators[validatorName].enabled = enabled;
+                this.updateStatus(field, this.STATUS_NOT_VALIDATED, validatorName);
+            }
+            // Enable/disable all validators
+            else if (!validatorName && this.options.fields[field].enabled !== enabled) {
                 this.options.fields[field].enabled = enabled;
-                this.updateStatus(field, this.STATUS_NOT_VALIDATED);
+                for (var v in validators) {
+                    this.enableFieldValidators(field, enabled, v);
+                }
             }
 
             return this;

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


+ 34 - 7
src/js/bootstrapValidator.js

@@ -592,6 +592,10 @@
             counter[this.STATUS_VALID]         = 0;
 
             for (var v in validators) {
+                if (validators[v].enabled === false) {
+                    continue;
+                }
+
                 numValidators++;
                 var result = $field.data('bv.result.' + v);
                 if (result) {
@@ -732,7 +736,7 @@
 
                     // Don't validate field if it is already done
                     var result = $field.data('bv.result.' + validatorName);
-                    if (result === this.STATUS_VALID || result === this.STATUS_INVALID) {
+                    if (result === this.STATUS_VALID || result === this.STATUS_INVALID || validators[validatorName].enabled === false) {
                         this._onFieldValidated($field, validatorName);
                         continue;
                     }
@@ -994,6 +998,10 @@
                 }
 
                 for (validatorName in this.options.fields[field].validators) {
+                    if (this.options.fields[field].validators[validatorName].enabled === false) {
+                        continue;
+                    }
+
                     status = $field.data('bv.result.' + validatorName);
                     if (status !== this.STATUS_VALID) {
                         return false;
@@ -1026,8 +1034,10 @@
                 if ($f.data('bv.messages')
                       .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]')
                       .filter(function() {
-                          var v = $(this).attr('data-bv-validator');
-                          return ($f.data('bv.result.' + v) && $f.data('bv.result.' + v) !== that.STATUS_VALID);
+                          var v = $(this).attr('data-bv-validator'),
+                              f = $(this).attr('data-bv-for');
+                          return (that.options.fields[f].validators[v].enabled !== false
+                                && $f.data('bv.result.' + v) && $f.data('bv.result.' + v) !== that.STATUS_VALID);
                       })
                       .length !== 0)
                 {
@@ -1055,6 +1065,7 @@
                     .val(this.$submitButton.val())
                     .appendTo(this.$form);
             }
+
             // Submit form
             this.$form.off('submit.bv').submit();
         },
@@ -1118,7 +1129,9 @@
                         .data('bv.messages')
                         .find('.help-block[data-bv-for="' + $(this).attr('data-bv-field') + '"][data-bv-result="' + that.STATUS_INVALID + '"]' + filter)
                         .map(function() {
-                            return $(this).html();
+                            var v = $(this).attr('data-bv-validator'),
+                                f = $(this).attr('data-bv-for');
+                            return (that.options.fields[f].validators[v].enabled === false) ? '' : $(this).html();
                         })
                         .get()
                 );
@@ -1306,12 +1319,26 @@
          *
          * @param {String} field The field name
          * @param {Boolean} enabled Enable/Disable field validators
+         * @param {String} [validatorName] The validator name. If null, all validators will be enabled/disabled
          * @returns {BootstrapValidator}
          */
-        enableFieldValidators: function(field, enabled) {
-            if (this.options.fields[field].enabled !== enabled) {
+        enableFieldValidators: function(field, enabled, validatorName) {
+            var validators = this.options.fields[field].validators;
+
+            // Enable/disable particular validator
+            if (validatorName
+                && validators
+                && validators[validatorName] && validators[validatorName].enabled !== enabled)
+            {
+                this.options.fields[field].validators[validatorName].enabled = enabled;
+                this.updateStatus(field, this.STATUS_NOT_VALIDATED, validatorName);
+            }
+            // Enable/disable all validators
+            else if (!validatorName && this.options.fields[field].enabled !== enabled) {
                 this.options.fields[field].enabled = enabled;
-                this.updateStatus(field, this.STATUS_NOT_VALIDATED);
+                for (var v in validators) {
+                    this.enableFieldValidators(field, enabled, v);
+                }
             }
 
             return this;

+ 104 - 0
test/spec.js

@@ -257,6 +257,110 @@ describe('container tooltip/popover', function() {
     });
 });
 
+describe('enable validators', function() {
+    beforeEach(function() {
+        $([
+            '<form class="form-horizontal" id="enableForm">',
+                '<div class="form-group">',
+                    '<input type="text" name="fullName" class="form-control" />',
+                '</div>',
+            '</form>'
+        ].join('\n')).appendTo('body');
+
+        $('#enableForm').bootstrapValidator({
+            fields: {
+                fullName: {
+                    validators: {
+                        notEmpty: {
+                            message: 'The full name is required and cannot be empty'
+                        },
+                        stringLength: {
+                            min: 8,
+                            max: 40,
+                            message: 'The full name must be more than 8 and less than 40 characters long'
+                        },
+                        regexp: {
+                            enabled: false,
+                            regexp: /^[a-zA-Z\s]+$/,
+                            message: 'The username can only consist of alphabetical, number, and space'
+                        }
+                    }
+                }
+            }
+        });
+
+        this.bv        = $('#enableForm').data('bootstrapValidator');
+        this.$fullName = this.bv.getFieldElements('fullName');
+    });
+
+    afterEach(function() {
+        $('#enableForm').bootstrapValidator('destroy').remove();
+    });
+
+    it('enable all validators', function() {
+        this.$fullName.val('@ $full N@m3');
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        this.bv.resetForm();
+        this.$fullName.val('Contain#$@');
+        this.bv.enableFieldValidators('fullName', true);
+        this.bv.validate();
+        expect(this.bv.isValidField('fullName')).toEqual(false);
+        expect(this.bv.isValid()).toEqual(false);
+    });
+
+    it('disable all validators', function() {
+        this.bv.resetForm();
+        this.bv.enableFieldValidators('fullName', false);
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+
+    it('enabled option particular validator', function() {
+        this.$fullName.val('Contain@#$');
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        var messages = this.bv.getMessages('fullName');
+        expect(messages.length).toEqual(0);
+    });
+
+    it('enable particular validators', function() {
+        // Enable stringLength validator
+        this.bv.resetForm();
+        this.bv.enableFieldValidators('fullName', true, 'stringLength');
+        this.bv.enableFieldValidators('fullName', true, 'regexp');
+        this.$fullName.val('Full@');
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+
+        var messages = this.bv.getMessages('fullName');
+        expect($.inArray('The full name must be more than 8 and less than 40 characters long', messages)).toBeGreaterThan(-1);
+        expect($.inArray('The username can only consist of alphabetical, number, and space', messages)).toBeGreaterThan(-1);
+    });
+
+    it('disable particular validators', function() {
+        // Disable stringLength validator
+        this.bv.enableFieldValidators('fullName', false, 'stringLength');
+        this.$fullName.val('Full');
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        var messages = this.bv.getMessages('fullName');
+        expect($.inArray('The full name must be more than 8 and less than 40 characters long', messages)).toEqual(-1);
+
+        // Disable regexp validator
+        this.bv.enableFieldValidators('fullName', false, 'regexp');
+        this.$fullName.val('Special@#$');
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        var messages = this.bv.getMessages('fullName');
+        expect($.inArray('The username can only consist of alphabetical, number, and space', messages)).toEqual(-1);
+    });
+});
+
 var My = {
     NameSpace: {
         onEmailValid: function(e, data) {

+ 103 - 0
test/spec/enable.js

@@ -0,0 +1,103 @@
+describe('enable validators', function() {
+    beforeEach(function() {
+        $([
+            '<form class="form-horizontal" id="enableForm">',
+                '<div class="form-group">',
+                    '<input type="text" name="fullName" class="form-control" />',
+                '</div>',
+            '</form>'
+        ].join('\n')).appendTo('body');
+
+        $('#enableForm').bootstrapValidator({
+            fields: {
+                fullName: {
+                    validators: {
+                        notEmpty: {
+                            message: 'The full name is required and cannot be empty'
+                        },
+                        stringLength: {
+                            min: 8,
+                            max: 40,
+                            message: 'The full name must be more than 8 and less than 40 characters long'
+                        },
+                        regexp: {
+                            enabled: false,
+                            regexp: /^[a-zA-Z\s]+$/,
+                            message: 'The username can only consist of alphabetical, number, and space'
+                        }
+                    }
+                }
+            }
+        });
+
+        this.bv        = $('#enableForm').data('bootstrapValidator');
+        this.$fullName = this.bv.getFieldElements('fullName');
+    });
+
+    afterEach(function() {
+        $('#enableForm').bootstrapValidator('destroy').remove();
+    });
+
+    it('enable all validators', function() {
+        this.$fullName.val('@ $full N@m3');
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        this.bv.resetForm();
+        this.$fullName.val('Contain#$@');
+        this.bv.enableFieldValidators('fullName', true);
+        this.bv.validate();
+        expect(this.bv.isValidField('fullName')).toEqual(false);
+        expect(this.bv.isValid()).toEqual(false);
+    });
+
+    it('disable all validators', function() {
+        this.bv.resetForm();
+        this.bv.enableFieldValidators('fullName', false);
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+    });
+
+    it('enabled option particular validator', function() {
+        this.$fullName.val('Contain@#$');
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        var messages = this.bv.getMessages('fullName');
+        expect(messages.length).toEqual(0);
+    });
+
+    it('enable particular validators', function() {
+        // Enable stringLength validator
+        this.bv.resetForm();
+        this.bv.enableFieldValidators('fullName', true, 'stringLength');
+        this.bv.enableFieldValidators('fullName', true, 'regexp');
+        this.$fullName.val('Full@');
+        this.bv.validate();
+        expect(this.bv.isValid()).toEqual(false);
+
+        var messages = this.bv.getMessages('fullName');
+        expect($.inArray('The full name must be more than 8 and less than 40 characters long', messages)).toBeGreaterThan(-1);
+        expect($.inArray('The username can only consist of alphabetical, number, and space', messages)).toBeGreaterThan(-1);
+    });
+
+    it('disable particular validators', function() {
+        // Disable stringLength validator
+        this.bv.enableFieldValidators('fullName', false, 'stringLength');
+        this.$fullName.val('Full');
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        var messages = this.bv.getMessages('fullName');
+        expect($.inArray('The full name must be more than 8 and less than 40 characters long', messages)).toEqual(-1);
+
+        // Disable regexp validator
+        this.bv.enableFieldValidators('fullName', false, 'regexp');
+        this.$fullName.val('Special@#$');
+        this.bv.validate();
+        expect(this.bv.isValid()).toBeTruthy();
+
+        var messages = this.bv.getMessages('fullName');
+        expect($.inArray('The username can only consist of alphabetical, number, and space', messages)).toEqual(-1);
+    });
+});