gpt4 book ai didi

javascript - 如何使用 AJV 创建自定义错误消息?

转载 作者:行者123 更新时间:2023-12-02 16:14:53 33 4
gpt4 key购买 nike

我正在尝试将自定义错误消息添加到我的应用程序输入字段,但是当我尝试获取此错误时:

Error: strict mode: unknown keyword: "errorMessage"

这是代码。

文件一:

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 : '',
}
}

文件二:

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),
}
}

我想要根据错误的不同消息,例如 minLength 或格式,但我想定义此错误消息的内容,我该怎么做?

最佳答案

您需要单独使用“ajv-errors”库。类似的东西:

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);

关于javascript - 如何使用 AJV 创建自定义错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67004894/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com