joi:定义多个自定义错误信息

目录

前言

原始版

基础错误版

复杂版

简单版


前言

在项目中,提交表单进行字段验证是必不可少的,在node项目中,自己写if else判断非常的繁琐,也不好进行维护,所以我们通常都会引入第三方包joi,来帮助我们进行表单字段的验证。

原始版

于是我写下了以下代码:

const username = joi.string().alphanum().min(1).max(10).required()

当然,验证是通过的,没有问题的,

username是一个字符串,值只能包含 a-zA-Z0-9,最小长度1,最大长度10,必填项。

利用postman发送请求,先看看会返回什么。

长度大于10的时候返回:

包含特殊字符的时候返回:

等等,还有很多,但都是返回的英文,虽然能读懂是什么含义,但是对于用户来讲,用户看不懂,于是要求返回中文

基础错误版

于是我又写了以下代码:

const username = joi.string().alphanum().min(1).max(10).required().error(new Error('用户名格式错误'))

postman请求一哈

然后吧,就发现任何错误的格式,返回的错误都是用户名格式错误,包括username为空,username参数不存在,username长度超出10等等 ,用户压根不知道自己犯了什么错。。。这种错误提示信息看来还是不行

复杂版

于是我又又写下了如下代码

const username = joi.string().alphanum().min(1).max(10).required().error(
    errors => {
        console.log(errors)
        for (err of errors) {
            console.log(err.code)
            switch (err.code) {
                case 'string.alphanum':
                    return new Error('只能包含a-zA-Z0-9')
                case 'string.max':
                    return new Error('用户名长度不能超过10')
                case 'string.empty':
                case 'any.required':
                    return new Error('用户名必填')
                default:
                    return new Error('用户名格式错误')
            }
        }
    }
)

 errors:

[
  {
    code: 'string.alphanum',
    flags: { presence: 'required', error: [Function (anonymous)] },
    messages: {
      'any.custom': [Object],
      'any.default': [Object],
      'any.failover': [Object],
      'any.invalid': [Object],
      'any.only': [Object],
      'any.ref': [Object],
      'any.required': [Object],
      'any.unknown': [Object],
      'string.alphanum': [Object],
      'string.base': [Object],
      'string.base64': [Object],
      'string.creditCard': [Object],
      'string.dataUri': [Object],
      'string.domain': [Object],
      'string.email': [Object],
      'string.empty': [Object],
      'string.guid': [Object],
      'string.hex': [Object],
      'string.hexAlign': [Object],
      'string.hostname': [Object],
      'string.ip': [Object],
      'string.ipVersion': [Object],
      'string.isoDate': [Object],
      'string.isoDuration': [Object],
      'string.length': [Object],
      'string.lowercase': [Object],
      'string.max': [Object],
      'string.min': [Object],
      'string.normalize': [Object],
      'string.token': [Object],
      'string.pattern.base': [Object],
      'string.pattern.name': [Object],
      'string.pattern.invert.base': [Object],
      'string.pattern.invert.name': [Object],
      'string.trim': [Object],
      'string.uri': [Object],
      'string.uriCustomScheme': [Object],
      'string.uriRelativeOnly': [Object],
      'string.uppercase': [Object]
    },
    path: [ 'username' ],
    prefs: {
      abortEarly: true,
      allowUnknown: true,
      artifacts: false,
      cache: true,
      context: null,
      convert: true,
      dateFormat: 'iso',
      errors: [Object],
      externals: true,
      messages: {},
      nonEnumerables: false,
      noDefaults: false,
      presence: 'optional',
      skipFunctions: false,
      stripUnknown: true,
      warnings: false
    },
    state: {
      path: [Array],
      ancestors: [Array],
      mainstay: [Object],
      schemas: null,
      debug: null
    },
    value: '%qwe',
    message: null,
    template: null,
    local: { label: 'username', value: '%qwe', key: 'username' }
  }
]

随后再用postman进行测试的时候,感觉这提示也太人性化了吧 0.0

 

简单版

后来经过查阅资料得知,还可以简单点

于是我又又又写下了如下代码:

const username = joi.string().alphanum().min(1).max(10).required().messages({
    "string.empty": "用户名必填",
    "any.required": "用户名必填",
    "string.alphanum": '只能包含a-zA-Z0-9',
    "string.max": '用户名长度不能超过10',
})

 经过测试,和error的模式是一样的,还挺不错!

猜你喜欢

转载自blog.csdn.net/qq_42543244/article/details/126605768