sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.56k stars 148 forks source link

email validation doesn't work? #879

Closed mblandr closed 1 month ago

mblandr commented 1 month ago

import { Type } from '@sinclair/typebox'; import { Value } from '@sinclair/typebox/value';

const T = Type.String({ format: 'email' }); const a = 'test@gmail.com'; const res = Value.Check(T, a); console.log(res); result is false.Why?

sinclairzx81 commented 1 month ago

@mblandr Hi,

TypeBox doesn't configure any strings formats by default, you will need to configure them yourself. The following configures the email format, you can add additional format checkers if you need.

import { Type, FormatRegistry } from '@sinclair/typebox'
import { Value } from '@sinclair/typebox/value'

FormatRegistry.Set('email', value => /^[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.test(value))

const Email = Type.String({ format: 'email' })

Value.Check(Email, "user@domain.com") // true
Value.Check(Email, "not-a-email")     // false

You can find some common formats here Hope this helps S

mblandr commented 1 month ago

Ok. thanks