Skip to content

Commit

Permalink
feat: 增加手机号及车牌号校验方法
Browse files Browse the repository at this point in the history
  • Loading branch information
Ares-Chang committed Aug 29, 2024
1 parent fe028fc commit e4f70ba
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/is/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,25 @@ export function isEmpty<T = unknown>(val: T): val is T {

return false
}

/**
* 判断是否为手机号
* @param val
* @returns 是否为手机号
* @example isMobileNum(13333333333) // => true
*/
export function isMobileNum(val: string | number): boolean {
return /^1[3-9]\d{9}$/.test(String(val))
}

/**
* 判断是否为车牌号
* @param val
* @returns 是否为车牌号
*/
export function isCarNo(val: string): boolean {
const oldPattern = /^[使A-Z][A-Z][A-Z0-9]{4}[A-Z0-9]$/
const newEnergyPattern = /^[使A-Z](?:(?:[A-Z](?![DF][0-9A-Z])[DF]|[A-Z]{2})[A-Z0-9]{5}|[A-Z0-9]{4}[DF])$/

return oldPattern.test(val) || newEnergyPattern.test(val)
}
36 changes: 35 additions & 1 deletion test/is/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
import { isEmpty } from '../../src/is/utils'
import {
isCarNo,
isEmpty,
isMobileNum,
} from '../../src/is/utils'

describe('is 工具函数测试', () => {
it('isEmpty 函数应正确判断空值', () => {
Expand All @@ -9,4 +13,34 @@ describe('is 工具函数测试', () => {
expect(isEmpty('')).toBe(true)
expect(isEmpty(null)).toBe(false)
})

it('isMobileNum 函数应正确判断手机号', () => {
expect(isMobileNum(17666666666)).toBe(true)
expect(isMobileNum('17666666666')).toBe(true)
expect(isMobileNum(12666666666)).toBe(false)
expect(isMobileNum(1266666666)).toBe(false)
})

it('isCarNo 函数应正确判断车牌号', () => {
expect(isCarNo('123')).toBe(false)

expect(isCarNo('京A12345')).toBe(true)
expect(isCarNo('川A123AB')).toBe(true)

expect(isCarNo('京A123456')).toBe(false)
expect(isCarNo('京A2222i')).toBe(false)

// 挂学警港澳
expect(isCarNo('京A2222学')).toBe(true)
expect(isCarNo('川AC001警')).toBe(true)
expect(isCarNo('川AC001挂')).toBe(true)

expect(isCarNo('川AC001京')).toBe(false)

// 新能源
expect(isCarNo('京DF12345')).toBe(true)
expect(isCarNo('京DD12345')).toBe(true)
expect(isCarNo('京DF1234D')).toBe(true)
expect(isCarNo('京DF1234F')).toBe(true)
})
})

0 comments on commit e4f70ba

Please sign in to comment.