我们在后台使用 Node.js,使用
Fastify
作为框架。
我们有满足的模式来验证使用的输入。
这里是模式,在 schema.ts
export const profileSchema = {
type: 'object',
properties: {
FirstName: {
type: 'string',
pattern: '^([a-zA-z]{2,100})+$'
},
LastName: {
type: 'string',
pattern: '^([a-zA-z]{2,100})+$'
},
MobilePhone: {
type: 'string',
pattern: '[0-9]{10}',
}
},
} as const
main.ts
import { profileSchema } from './schema'
const app = fastify()
app.post(`/createProfile`,
{
schema: {
body: profileSchema,
}
},
createProfile
)
然而,当我们将手机号码作为 Number 而不是 String 传递时,它仍然在工作而不是抛出 error
{
"FirstName": "John",
"LastName": "Doe",
"MobilePhone": 9876543210
}
理想情况下,因为我们将手机号码作为数字传递,模式应该验证并抛出错误。
coerceTypes
设置为 false
const app = require('fastify')({
... // other settings
ajv: {
customOptions: {
coerceTypes: false,
}
}
})
默认情况下,这将禁用对所有路由和所有模式的强制。如果您只需要禁用特定路由或模式的强制,您可以使用setValidatorCompiler
功能