Skip to content

Commit

Permalink
feat: support z.regExp()
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jan 25, 2025
1 parent 39f0ee7 commit ceaab23
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ declare global {
percent(): Schema<number>
boolean(): Schema<boolean>
date(): Schema<string | Date, Date>
regExp(flag?: string): Schema<string | RegExp, RegExp>
bitset<K extends string>(bits: Partial<Record<K, number>>): Schema<number | readonly K[], number>
function(): Schema<Function, (...args: any[]) => any>
is<T>(constructor: Constructor<T>): Schema<T>
Expand Down Expand Up @@ -443,6 +444,19 @@ Schema.date = function date() {
])
}

Schema.regExp = function regExp(flag = '') {
return Schema.union([
Schema.is(RegExp),
Schema.transform(Schema.string().role('regexp', { flag }), (value, options) => {
try {
return new RegExp(value, flag)
} catch (e: any) {
throw new ValidationError(e.message, options)
}
}, true),
])
}

Schema.extend('any', (data) => {
return [data]
})
Expand All @@ -452,7 +466,7 @@ Schema.extend('never', (data, _, options) => {
})

Schema.extend('const', (data, { value }, options) => {
if (data === value) return [value]
if (deepEqual(data, value)) return [value]
throw new ValidationError(`expected ${value} but got ${data}`, options)
})

Expand Down
22 changes: 22 additions & 0 deletions packages/core/tests/regexp.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { describe, test } from 'node:test'
import { expect } from 'chai'
import Schema from 'schemastery'

describe('RegExp', () => {
test('z.regExp()', () => {
const Config = Schema.object({
re: Schema.regExp('i'),
})

const obj1 = { re: /foo/g }
expect(new Config(obj1)).to.deep.equal({ re: /foo/g })
expect(obj1).to.deep.equal({ re: /foo/g })

const obj2 = { re: 'bar' }
expect(new Config(obj2)).to.deep.equal({ re: /bar/i })
expect(obj2).to.deep.equal({ re: 'bar' })

const obj3 = { re: '+' }
expect(() => new Config(obj3)).to.throw()
})
})

0 comments on commit ceaab23

Please # to comment.