stringLength.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. (function($) {
  2. $.fn.bootstrapValidator.i18n.stringLength = $.extend($.fn.bootstrapValidator.i18n.stringLength || {}, {
  3. 'default': 'The value length is not valid',
  4. less: 'The value must be less than %s characters long',
  5. more: 'The value must be more than %s characters long',
  6. between: 'The value must be between %s and %s characters long',
  7. getMessage: function(options) {
  8. switch (true) {
  9. case (!!options.min && !!options.max):
  10. return $.fn.bootstrapValidator.helpers.format(this.between, [options.min, options.max]);
  11. break;
  12. case (!!options.min):
  13. return $.fn.bootstrapValidator.helpers.format(this.more, options.min);
  14. case (!!options.max):
  15. return $.fn.bootstrapValidator.helpers.format(this.less, options.max);
  16. default:
  17. return this['default'];
  18. }
  19. }
  20. });
  21. $.fn.bootstrapValidator.validators.stringLength = {
  22. html5Attributes: {
  23. message: 'message',
  24. min: 'min',
  25. max: 'max'
  26. },
  27. enableByHtml5: function($field) {
  28. var maxLength = $field.attr('maxlength');
  29. if (maxLength) {
  30. return {
  31. max: parseInt(maxLength, 10)
  32. };
  33. }
  34. return false;
  35. },
  36. /**
  37. * Check if the length of element value is less or more than given number
  38. *
  39. * @param {BootstrapValidator} validator The validator plugin instance
  40. * @param {jQuery} $field Field element
  41. * @param {Object} options Consists of following keys:
  42. * - min
  43. * - max
  44. * At least one of two keys is required
  45. * - message: The invalid message
  46. * @returns {Boolean}
  47. */
  48. validate: function(validator, $field, options) {
  49. var value = $field.val();
  50. if (value == '') {
  51. return true;
  52. }
  53. var length = $.trim(value).length;
  54. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  55. return false;
  56. }
  57. return true;
  58. }
  59. };
  60. }(window.jQuery));