phone.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. (function($) {
  2. $.fn.bootstrapValidator.validators.phone = {
  3. html5Attributes: {
  4. message: 'message',
  5. country: 'country'
  6. },
  7. /**
  8. * Return true if the input value contains a valid US phone number only
  9. *
  10. * @param {BootstrapValidator} validator Validate plugin instance
  11. * @param {jQuery} $field Field element
  12. * @param {Object} options Consist of key:
  13. * - message: The invalid message
  14. * - country: The ISO 3166 country code
  15. * Currently it only supports United State (US) country
  16. * @returns {Boolean}
  17. */
  18. validate: function(validator, $field, options) {
  19. var value = $field.val();
  20. if (value == '') {
  21. return true;
  22. }
  23. var country = (options.country || 'US').toUpperCase();
  24. switch (country) {
  25. case 'US':
  26. default:
  27. // Make sure US phone numbers have 10 digits
  28. // May start with 1, +1, or 1-; should discard
  29. // Area code may be delimited with (), & sections may be delimited with . or -
  30. // Test: http://regexr.com/38mqi
  31. value = value.replace(/\(|\)|\s+/g, '');
  32. return (/^(?:(1\-?)|(\+1 ?))?\(?(\d{3})[\)\-\.]?(\d{3})[\-\.]?(\d{4})$/).test(value) && (value.length == 10);
  33. }
  34. }
  35. }
  36. }(window.jQuery));