[英]How to create custom error messages using AJV?
I am trying to add custom error messages to my application input field but when I try to get this error:我正在尝试将自定义错误消息添加到我的应用程序输入字段,但是当我尝试收到此错误时:
Error: strict mode: unknown keyword: "errorMessage"错误:严格模式:未知关键字:“errorMessage”
Here's the code.这是代码。
file one:文件一:
import Ajv, { JSONSchemaType } from 'ajv'
import addFormats from 'ajv-formats'
const ajv = new Ajv({ allErrors: true, $data: true })
addFormats(ajv)
export const emailSchema: JSONSchemaType<string> = {
type: 'string',
minLength: 1,
format: 'email',
//this is whats causing the error
errorMessage: {
minLength: 'This field cannot be empty.',
format: 'Must be a valid email address.',
},
}
export const validateEmail = (value: string) => {
return {
isValid: emailValidator(value),
error: emailValidator.errors ? emailValidator.errors[0]?.message : '',
}
}
file two:文件二:
import Ajv, { JSONSchemaType } from 'ajv'
import { LoginCredentials } from './types'
import addFormats from 'ajv-formats'
import {
emailSchema,
passwordSchema,
recaptchaTockenSchema,
} from '../../utils/validation/auth-validation'
import { getFormattedErrors } from '../../utils/validation/formatter'
const ajv = new Ajv({ allErrors: true, $data: true })
addFormats(ajv)
const credentialsSchema: JSONSchemaType<LoginCredentials> = {
type: 'object',
properties: {
emailAddress: emailSchema,
password: passwordSchema,
recaptchaToken: recaptchaTockenSchema,
},
required: ['emailAddress', 'password', 'recaptchaToken'],
additionalProperties: false,
}
const credentialsValidator = ajv.compile(credentialsSchema)
export const validateCredentials = (credentials: LoginCredentials) => {
return {
isValid: credentialsValidator(credentials),
errors: getFormattedErrors(credentialsValidator.errors),
}
}
I would like a different message depending on the error for instance minLength or format but I would like to define what this error message says, how can I do this?我想要一条不同的消息,具体取决于错误,例如 minLength 或格式,但我想定义这个错误消息的内容,我该怎么做?
you need to use 'ajv-errors' lib separately.您需要单独使用“ajv-errors”库。 Something like that:像这样的东西:
import Ajv from 'ajv';
import addFormats from 'ajv-formats'
import ajvErrors from 'ajv-errors';
const ajv = new Ajv({ allErrors: true, $data: true });
addFormats(ajv);
ajvErrors(ajv);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.