Skip to content

Commit

Permalink
feat(utils): 新增 isCuid2
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Dec 8, 2023
1 parent 0241337 commit 8bcca66
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export * from './inTaro'
export * from './inWechatWebView'
export * from './isBlobUrl'
export * from './isChineseIDCardNumber'
export * from './isCuid'
export * from './isCuid2'
export * from './isDataUrl'
export * from './isElementVisible'
export * from './isEmail'
Expand Down
10 changes: 10 additions & 0 deletions src/utils/isCuid2.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { isCuid2 } from './isCuid2'

describe('isCuid2', () => {
test('ok', () => {
expect(isCuid2('tz4a98xxat96iws9zmbrgj3a')).toBeTrue()

expect(isCuid2('1')).toBeFalse()
expect(isCuid2('tz4aws9zmbrgj3a')).toBeFalse()
})
})
35 changes: 35 additions & 0 deletions src/utils/isCuid2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const re = /^[0-9a-z]+$/

export interface IsCuid2Options {
/**
* @default 24
*/
minLength?: number
/**
* @default 24
*/
maxLength?: number
}

/**
* 检测传入值是否是 Cuid2。
*
* @param value 要检测的值
* @returns 返回检测结果
* @example
* ```typescript
* isCuid2('1') // => false
* isCuid2('tz4a98xxat96iws9zmbrgj3a') // => true
* ```
* @see https://github.com/paralleldrive/cuid2
*/
export function isCuid2(value: string, options: IsCuid2Options = {}): boolean {
const { minLength = 24, maxLength = 24 } = options
return (
!!value &&
typeof value === 'string' &&
value.length >= minLength &&
value.length <= maxLength &&
re.test(value)
)
}

0 comments on commit 8bcca66

Please sign in to comment.