Browse Source

#465: Refactoring phone validator

phuoc 11 years ago
parent
commit
703937b4e3

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

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

+ 37 - 28
dist/js/bootstrapValidator.js

@@ -2,7 +2,7 @@
  * BootstrapValidator (http://bootstrapvalidator.com)
  * BootstrapValidator (http://bootstrapvalidator.com)
  * The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3
  * The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3
  *
  *
- * @version     v0.5.0-dev, built on 2014-07-06 9:00:01 AM
+ * @version     v0.5.0-dev, built on 2014-07-06 9:18:35 AM
  * @author      https://twitter.com/nghuuphuoc
  * @author      https://twitter.com/nghuuphuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @license     MIT
  * @license     MIT
@@ -4293,19 +4293,6 @@
         countries: {
         countries: {
             GB: 'United Kingdom',
             GB: 'United Kingdom',
             US: 'USA'
             US: 'USA'
-        },
-
-        getMessage: function(options) {
-            var country = (options.country || 'US').toUpperCase();
-            if ($.inArray(country, $.fn.bootstrapValidator.validators.phone.COUNTRIES) === -1) {
-                return $.fn.bootstrapValidator.helpers.format(this.countryNotSupported, country);
-            }
-
-            if (this.countries[country]) {
-                return $.fn.bootstrapValidator.helpers.format(this.country, this.countries[country]);
-            }
-
-            return this['default'];
         }
         }
     });
     });
 
 
@@ -4316,7 +4303,7 @@
         },
         },
 
 
         // The supported countries
         // The supported countries
-        COUNTRIES: ['GB', 'US'],
+        COUNTRY_CODES: ['GB', 'US'],
 
 
         /**
         /**
          * Return true if the input value contains a valid phone number for the country
          * Return true if the input value contains a valid phone number for the country
@@ -4326,9 +4313,14 @@
          * @param {jQuery} $field Field element
          * @param {jQuery} $field Field element
          * @param {Object} options Consist of key:
          * @param {Object} options Consist of key:
          * - message: The invalid message
          * - message: The invalid message
-         * - country: The ISO 3166 country code
+         * - country: The ISO-3166 country code. It can be
+         *      - A country code
+         *      - Name of field which its value defines the country code
+         *      - Name of callback function that returns the country code
+         *      - A callback function that returns the country code
+         *
          * Currently it only supports United State (US) or United Kingdom (GB) countries
          * Currently it only supports United State (US) or United Kingdom (GB) countries
-         * @returns {Boolean}
+         * @returns {Boolean|Object}
          */
          */
         validate: function(validator, $field, options) {
         validate: function(validator, $field, options) {
             var value = $field.val();
             var value = $field.val();
@@ -4336,17 +4328,28 @@
                 return true;
                 return true;
             }
             }
 
 
-            var country = (options.country || 'US').toUpperCase();
-            if ($.inArray(country, this.COUNTRIES) === -1) {
-                return false;
+            var country = options.country;
+            if (typeof country !== 'string' || $.inArray(country, this.COUNTRY_CODES) === -1) {
+                // Try to determine the country
+                country = validator.getDynamicOption(country, $field);
             }
             }
 
 
-            switch (country) {
+            if (!country || $.inArray(country.toUpperCase(), this.COUNTRY_CODES) === -1) {
+                return {
+                    valid: false,
+                    message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.phone.countryNotSupported, country)
+                };
+            }
+
+            var isValid = true;
+            switch (country.toUpperCase()) {
             	case 'GB':
             	case 'GB':
             		// http://aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers#Match_GB_telephone_number_in_any_format
             		// http://aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers#Match_GB_telephone_number_in_any_format
             		// Test: http://regexr.com/38uhv
             		// Test: http://regexr.com/38uhv
-            		value = $.trim(value);
-            		return (/^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$/).test(value);
+            		value   = $.trim(value);
+            		isValid = (/^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$/).test(value);
+                    break;
+
                 case 'US':
                 case 'US':
                 /* falls through */
                 /* falls through */
                 default:
                 default:
@@ -4354,9 +4357,15 @@
                     // May start with 1, +1, or 1-; should discard
                     // May start with 1, +1, or 1-; should discard
                     // Area code may be delimited with (), & sections may be delimited with . or -
                     // Area code may be delimited with (), & sections may be delimited with . or -
                     // Test: http://regexr.com/38mqi
                     // Test: http://regexr.com/38mqi
-                    value = value.replace(/\D/g, '');
-                    return (/^(?:(1\-?)|(\+1 ?))?\(?(\d{3})[\)\-\.]?(\d{3})[\-\.]?(\d{4})$/).test(value) && (value.length === 10);
+                    value   = value.replace(/\D/g, '');
+                    isValid = (/^(?:(1\-?)|(\+1 ?))?\(?(\d{3})[\)\-\.]?(\d{3})[\-\.]?(\d{4})$/).test(value) && (value.length === 10);
+                    break;
             }
             }
+
+            return {
+                valid: isValid,
+                message: $.fn.bootstrapValidator.helpers.format(options.message || $.fn.bootstrapValidator.i18n.phone.country, $.fn.bootstrapValidator.i18n.phone.countries[country])
+            };
         }
         }
     };
     };
 }(window.jQuery));
 }(window.jQuery));
@@ -6226,7 +6235,7 @@
             country: 'country'
             country: 'country'
         },
         },
 
 
-        COUNTRIES: ['CA', 'DK', 'GB', 'IT', 'NL', 'SE', 'SG', 'US'],
+        COUNTRY_CODES: ['CA', 'DK', 'GB', 'IT', 'NL', 'SE', 'SG', 'US'],
 
 
         /**
         /**
          * Return true if and only if the input value is a valid country zip code
          * Return true if and only if the input value is a valid country zip code
@@ -6268,12 +6277,12 @@
             }
             }
 
 
             var country = options.country;
             var country = options.country;
-            if (typeof country !== 'string' || $.inArray(country, this.COUNTRIES) === -1) {
+            if (typeof country !== 'string' || $.inArray(country, this.COUNTRY_CODES) === -1) {
                 // Try to determine the country
                 // Try to determine the country
                 country = validator.getDynamicOption(country, $field);
                 country = validator.getDynamicOption(country, $field);
             }
             }
 
 
-            if (!country || $.inArray(country.toUpperCase(), this.COUNTRIES) === -1) {
+            if (!country || $.inArray(country.toUpperCase(), this.COUNTRY_CODES) === -1) {
                 return { valid: false, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.zipCode.countryNotSupported, country) };
                 return { valid: false, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.zipCode.countryNotSupported, country) };
             }
             }
 
 

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


+ 33 - 24
src/js/validator/phone.js

@@ -6,19 +6,6 @@
         countries: {
         countries: {
             GB: 'United Kingdom',
             GB: 'United Kingdom',
             US: 'USA'
             US: 'USA'
-        },
-
-        getMessage: function(options) {
-            var country = (options.country || 'US').toUpperCase();
-            if ($.inArray(country, $.fn.bootstrapValidator.validators.phone.COUNTRIES) === -1) {
-                return $.fn.bootstrapValidator.helpers.format(this.countryNotSupported, country);
-            }
-
-            if (this.countries[country]) {
-                return $.fn.bootstrapValidator.helpers.format(this.country, this.countries[country]);
-            }
-
-            return this['default'];
         }
         }
     });
     });
 
 
@@ -29,7 +16,7 @@
         },
         },
 
 
         // The supported countries
         // The supported countries
-        COUNTRIES: ['GB', 'US'],
+        COUNTRY_CODES: ['GB', 'US'],
 
 
         /**
         /**
          * Return true if the input value contains a valid phone number for the country
          * Return true if the input value contains a valid phone number for the country
@@ -39,9 +26,14 @@
          * @param {jQuery} $field Field element
          * @param {jQuery} $field Field element
          * @param {Object} options Consist of key:
          * @param {Object} options Consist of key:
          * - message: The invalid message
          * - message: The invalid message
-         * - country: The ISO 3166 country code
+         * - country: The ISO-3166 country code. It can be
+         *      - A country code
+         *      - Name of field which its value defines the country code
+         *      - Name of callback function that returns the country code
+         *      - A callback function that returns the country code
+         *
          * Currently it only supports United State (US) or United Kingdom (GB) countries
          * Currently it only supports United State (US) or United Kingdom (GB) countries
-         * @returns {Boolean}
+         * @returns {Boolean|Object}
          */
          */
         validate: function(validator, $field, options) {
         validate: function(validator, $field, options) {
             var value = $field.val();
             var value = $field.val();
@@ -49,17 +41,28 @@
                 return true;
                 return true;
             }
             }
 
 
-            var country = (options.country || 'US').toUpperCase();
-            if ($.inArray(country, this.COUNTRIES) === -1) {
-                return false;
+            var country = options.country;
+            if (typeof country !== 'string' || $.inArray(country, this.COUNTRY_CODES) === -1) {
+                // Try to determine the country
+                country = validator.getDynamicOption(country, $field);
+            }
+
+            if (!country || $.inArray(country.toUpperCase(), this.COUNTRY_CODES) === -1) {
+                return {
+                    valid: false,
+                    message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.phone.countryNotSupported, country)
+                };
             }
             }
 
 
-            switch (country) {
+            var isValid = true;
+            switch (country.toUpperCase()) {
             	case 'GB':
             	case 'GB':
             		// http://aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers#Match_GB_telephone_number_in_any_format
             		// http://aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers#Match_GB_telephone_number_in_any_format
             		// Test: http://regexr.com/38uhv
             		// Test: http://regexr.com/38uhv
-            		value = $.trim(value);
-            		return (/^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$/).test(value);
+            		value   = $.trim(value);
+            		isValid = (/^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$/).test(value);
+                    break;
+
                 case 'US':
                 case 'US':
                 /* falls through */
                 /* falls through */
                 default:
                 default:
@@ -67,9 +70,15 @@
                     // May start with 1, +1, or 1-; should discard
                     // May start with 1, +1, or 1-; should discard
                     // Area code may be delimited with (), & sections may be delimited with . or -
                     // Area code may be delimited with (), & sections may be delimited with . or -
                     // Test: http://regexr.com/38mqi
                     // Test: http://regexr.com/38mqi
-                    value = value.replace(/\D/g, '');
-                    return (/^(?:(1\-?)|(\+1 ?))?\(?(\d{3})[\)\-\.]?(\d{3})[\-\.]?(\d{4})$/).test(value) && (value.length === 10);
+                    value   = value.replace(/\D/g, '');
+                    isValid = (/^(?:(1\-?)|(\+1 ?))?\(?(\d{3})[\)\-\.]?(\d{3})[\-\.]?(\d{4})$/).test(value) && (value.length === 10);
+                    break;
             }
             }
+
+            return {
+                valid: isValid,
+                message: $.fn.bootstrapValidator.helpers.format(options.message || $.fn.bootstrapValidator.i18n.phone.country, $.fn.bootstrapValidator.i18n.phone.countries[country])
+            };
         }
         }
     };
     };
 }(window.jQuery));
 }(window.jQuery));

+ 3 - 3
src/js/validator/zipCode.js

@@ -21,7 +21,7 @@
             country: 'country'
             country: 'country'
         },
         },
 
 
-        COUNTRIES: ['CA', 'DK', 'GB', 'IT', 'NL', 'SE', 'SG', 'US'],
+        COUNTRY_CODES: ['CA', 'DK', 'GB', 'IT', 'NL', 'SE', 'SG', 'US'],
 
 
         /**
         /**
          * Return true if and only if the input value is a valid country zip code
          * Return true if and only if the input value is a valid country zip code
@@ -63,12 +63,12 @@
             }
             }
 
 
             var country = options.country;
             var country = options.country;
-            if (typeof country !== 'string' || $.inArray(country, this.COUNTRIES) === -1) {
+            if (typeof country !== 'string' || $.inArray(country, this.COUNTRY_CODES) === -1) {
                 // Try to determine the country
                 // Try to determine the country
                 country = validator.getDynamicOption(country, $field);
                 country = validator.getDynamicOption(country, $field);
             }
             }
 
 
-            if (!country || $.inArray(country.toUpperCase(), this.COUNTRIES) === -1) {
+            if (!country || $.inArray(country.toUpperCase(), this.COUNTRY_CODES) === -1) {
                 return { valid: false, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.zipCode.countryNotSupported, country) };
                 return { valid: false, message: $.fn.bootstrapValidator.helpers.format($.fn.bootstrapValidator.i18n.zipCode.countryNotSupported, country) };
             }
             }
 
 

+ 1 - 2
test/spec.js

@@ -336,7 +336,6 @@ describe('enable validators', function() {
         expect(this.bv.isValid()).toEqual(false);
         expect(this.bv.isValid()).toEqual(false);
 
 
         var messages = this.bv.getMessages('fullName');
         var messages = this.bv.getMessages('fullName');
-        console.log(messages);
         expect($.inArray('The full name must be more than 8 and less than 40 characters long', messages)).toBeGreaterThan(-1);
         expect($.inArray('The full name must be more than 8 and less than 40 characters long', messages)).toBeGreaterThan(-1);
         expect($.inArray('The full name can only consist of alphabetical, number, and space', messages)).toBeGreaterThan(-1);
         expect($.inArray('The full name can only consist of alphabetical, number, and space', messages)).toBeGreaterThan(-1);
     });
     });
@@ -1282,7 +1281,7 @@ describe('i18n', function() {
         this.bv.resetForm();
         this.bv.resetForm();
         this.$phone.val('123456');
         this.$phone.val('123456');
         this.bv.validate();
         this.bv.validate();
-        expect(this.bv.getMessages('phoneNumber', 'phone')[0]).toEqual(i18n.phone.getMessage({ country: 'US' }));
+        expect(this.bv.getMessages('phoneNumber', 'phone')[0]).toEqual(format(i18n.phone.country, i18n.phone.countries['US']));
 
 
         this.bv.resetForm();
         this.bv.resetForm();
         this.$program.eq(0).prop('checked', 'checked');
         this.$program.eq(0).prop('checked', 'checked');

+ 0 - 1
test/spec/enable.js

@@ -77,7 +77,6 @@ describe('enable validators', function() {
         expect(this.bv.isValid()).toEqual(false);
         expect(this.bv.isValid()).toEqual(false);
 
 
         var messages = this.bv.getMessages('fullName');
         var messages = this.bv.getMessages('fullName');
-        console.log(messages);
         expect($.inArray('The full name must be more than 8 and less than 40 characters long', messages)).toBeGreaterThan(-1);
         expect($.inArray('The full name must be more than 8 and less than 40 characters long', messages)).toBeGreaterThan(-1);
         expect($.inArray('The full name can only consist of alphabetical, number, and space', messages)).toBeGreaterThan(-1);
         expect($.inArray('The full name can only consist of alphabetical, number, and space', messages)).toBeGreaterThan(-1);
     });
     });

+ 1 - 1
test/spec/i18n.js

@@ -308,7 +308,7 @@ describe('i18n', function() {
         this.bv.resetForm();
         this.bv.resetForm();
         this.$phone.val('123456');
         this.$phone.val('123456');
         this.bv.validate();
         this.bv.validate();
-        expect(this.bv.getMessages('phoneNumber', 'phone')[0]).toEqual(i18n.phone.getMessage({ country: 'US' }));
+        expect(this.bv.getMessages('phoneNumber', 'phone')[0]).toEqual(format(i18n.phone.country, i18n.phone.countries['US']));
 
 
         this.bv.resetForm();
         this.bv.resetForm();
         this.$program.eq(0).prop('checked', 'checked');
         this.$program.eq(0).prop('checked', 'checked');