id.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. (function($) {
  2. $.fn.bootstrapValidator.validators.id = {
  3. html5Attributes: {
  4. message: 'message',
  5. country: 'country'
  6. },
  7. /**
  8. * Validate identification number in different countries
  9. *
  10. * @param {BootstrapValidator} validator The validator 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-1 country code
  15. * @returns {Boolean}
  16. */
  17. validate: function(validator, $field, options) {
  18. var value = $field.val();
  19. if (value == '') {
  20. return true;
  21. }
  22. var country = options.country || value.substr(0, 2),
  23. method = ['_', country.toLowerCase()].join('');
  24. if (this[method] && 'function' == typeof this[method]) {
  25. return this[method](value);
  26. }
  27. return true;
  28. },
  29. /**
  30. * Validate Brazilian ID (CFP)
  31. * Examples:
  32. * - Valid: 39053344705, 390.533.447-05, 111.444.777-35
  33. * - Invalid: 231.002.999-00
  34. *
  35. * @see http://en.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas
  36. * @param {String} value The ID
  37. * @returns {Boolean}
  38. */
  39. _br: function(value) {
  40. if (/^1{11}|2{11}|3{11}|4{11}|5{11}|6{11}|7{11}|8{11}|9{11}|0{11}$/.test(value)) {
  41. return false;
  42. }
  43. if (!/^\d{11}$/.test(value) && !/^\d{3}\.\d{3}\.\d{3}-\d{2}$/.test(value)) {
  44. return false;
  45. }
  46. value = value.replace(/\./g, '').replace(/-/g, '');
  47. var d1 = 0;
  48. for (var i = 0; i < 9; i++) {
  49. d1 += (10 - i) * parseInt(value.charAt(i));
  50. }
  51. d1 = 11 - d1 % 11;
  52. if (d1 == 10 || d1 == 11) {
  53. d1 = 0;
  54. }
  55. if (d1 != value.charAt(9)) {
  56. return false;
  57. }
  58. var d2 = 0;
  59. for (i = 0; i < 10; i++) {
  60. d2 += (11 - i) * parseInt(value.charAt(i));
  61. }
  62. d2 = 11 - d2 % 11;
  63. if (d2 == 10 || d2 == 11) {
  64. d2 = 0;
  65. }
  66. return (d2 == value.charAt(10));
  67. }
  68. };
  69. }(window.jQuery));