sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.77k stars 152 forks source link

[Feature Request?] allow more flexible input for string pattern #746

Closed sabercoy closed 7 months ago

sabercoy commented 7 months ago

I would like to define a pattern that is a regex that ignores case

const test = Type.Object({
  email: Type.String({
    pattern: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i
  })
})

but pattern expects a string, and there is no way to express this regex as a string (that I know of) that can specify to ignore case. The implementation seems to be to take the pattern and wrap it in new RegExp, but what this does is wrap the string with slashes, so there is no way to get the "i" at the end.

So could pattern allow a type that would make this possible?

sinclairzx81 commented 7 months ago

@sabercoy Hi, Try the RegExp type.

const test = Type.Object({
  email: Type.RegExp(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i)
})

Just note that the string pattern is limited to the ECMA 262 subset supported by Json Schema while the RegExp type offers full UTF-16 + flags support (but comes at a cost of not being compliant with Json Schema)

Hope this helps S

sabercoy commented 7 months ago

Hi, Try the RegExp type.

Wow I didn't even think to use Type.RegExp in there. It looks like this works. I see, the pattern should be compliant with that standard, that's understandable.

THANKS SO MUCH! I love the project.

sinclairzx81 commented 7 months ago

@sabercoy All good :)

Will close off this issue for now All the best! S