index.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // @ts-nocheck
  2. // import assertString from './util/assertString';
  3. /**
  4. * 字节长度验证配置选项
  5. */
  6. export type IsByteLengthOptions = {
  7. /** 允许的最小字节长度 */
  8. min ?: number;
  9. /** 允许的最大字节长度 */
  10. max ?: number;
  11. }
  12. /**
  13. * 检查字符串字节长度是否在指定范围内
  14. * @function
  15. * @overload 使用配置对象
  16. * @param str - 要检查的字符串
  17. * @param options - 配置选项对象
  18. * @returns 是否满足字节长度要求
  19. *
  20. * @overload 使用独立参数
  21. * @param str - 要检查的字符串
  22. * @param min - 最小字节长度
  23. * @param max - 最大字节长度(可选)
  24. * @returns 是否满足字节长度要求
  25. *
  26. * @example
  27. * // 使用配置对象
  28. * isByteLength('🇨🇳', { min: 4, max: 8 }); // true(unicode 国旗符号占 8 字节)
  29. *
  30. * @example
  31. * // 旧式参数调用
  32. * isByteLength('hello', 3, 7); // true(实际字节长度 5)
  33. *
  34. * @description
  35. * 1. 使用 URL 编码计算字节长度(更准确处理多字节字符)
  36. * 2. 同时支持两种参数格式:
  37. * - 配置对象格式 { min, max }
  38. * - 独立参数格式 (min, max)
  39. * 3. 不传 max 参数时只验证最小长度
  40. * 4. 严格空值处理,允许设置 0 值
  41. */
  42. export function isByteLength(str : string, optionsOrMin ?: IsByteLengthOptions) : boolean;
  43. export function isByteLength(str : string, optionsOrMin ?: number) : boolean;
  44. export function isByteLength(str : string, optionsOrMin : number, maxParam : number | null) : boolean;
  45. export function isByteLength(
  46. str : string,
  47. optionsOrMin ?: IsByteLengthOptions | number,
  48. maxParam : number | null = null
  49. ) : boolean {
  50. // assertString(str);
  51. /** 最终计算的最小长度 */
  52. let min: number;
  53. /** 最终计算的最大长度 */
  54. let max : number | null;
  55. // 参数逻辑处理
  56. if (optionsOrMin != null && typeof optionsOrMin == 'object') {
  57. // 使用对象配置的情况
  58. const options = optionsOrMin as IsByteLengthOptions;
  59. min = Math.max(options.min ?? 0, 0); // 确保最小值为正整数
  60. max = options.max;
  61. } else {
  62. // 使用独立参数的情况
  63. min = Math.max(
  64. typeof optionsOrMin == 'number' ? optionsOrMin : 0,
  65. 0
  66. );
  67. max = maxParam;
  68. }
  69. // URL 编码后的字节长度计算
  70. const encoded = encodeURI(str);
  71. const len = (encoded?.split(/%..|./).length ?? 0) - 1;
  72. // 执行验证逻辑
  73. // #ifndef APP-ANDROID
  74. return len >= min && (typeof max == 'undefined' || len <= (max ?? 0));
  75. // #endif
  76. // #ifdef APP-ANDROID
  77. return len >= min && (max == null || len <= max);
  78. // #endif
  79. }