Joi 验证错误来自哪个字段,在 UI 中在其旁边显示错误

Uma*_*til 2 javascript node.js joi hapi.js

我必须使用 Joi 验证库来验证 API 输入,然后发送输出。

我说过创建了一个架构如下:

import Joi from '@hapi/joi'

const eventSchema = Joi.object({
  title: Joi.string()
    .min(7)
    .max(50)
    .required()
    .error(() => Error('Event title has to be least 7 and max 50 characters.')),

  description: Joi.string()
    .min(10)
    .max(400)
    .required()
    .error(() => Error('Event description has to be least 10 and max 400 characters.')),

  place: Joi.string()
    .min(6)
    .max(40)
    .required()
    .error(() => Error('Event place has to be least 6 and max 40 characters.'))
})
export default eventSchema
Run Code Online (Sandbox Code Playgroud)

当我验证这一点时,我收到了预期的验证错误。这里的问题是我不知道哪个字段真正导致了错误。我想知道这一点,因为我想准确地在导致错误的字段旁边显示错误,而不是仅在表单顶部显示通用验证消息。

const isValid = eventSchema.validate()

if (isValid.error) {
  const fieldNameWhichCauseError = ???

  return {
   errors: { [fieldNameWhichCauseError]: isValid.error.message }
  }
}

// Everything looks good save to db
// ...etc.
Run Code Online (Sandbox Code Playgroud)

上面的代码现在可以知道fieldNameWhichCauseError = ???中的字段名称。。有人能帮帮我吗?我还没见过有人做过这样的场景。我在文档中也没有找到。我有很多架构和验证,这确实阻碍了我在 UI 中的正确位置显示错误。

Uma*_*til 6

我自己想出来了。有一天它可能会帮助有人在这里搜索。

首先,我将创建一个自定义 ValidationError 对象。

class ValidationError extends Error {
   constructor(message, fieldName) {
     super(message)
     this.fieldName = fieldName
   }
}
Run Code Online (Sandbox Code Playgroud)

现在在问题中发布的上述代码中使用此类。使用 ValidationError 而不是 Error 类,并将字段名称传递给它。例子

const eventSchema = Joi.object({
  title: Joi.string()
    .min(7)
    .max(50)
    .required()
    .error(() => new ValidationError('Event title has to be least 7 and max 50 characters.', 'title'))
})
Run Code Online (Sandbox Code Playgroud)

使用自定义类时请记住使用new。验证的代码可以error.fieldName从传递下来的错误对象中获取值。

我希望这是正确的方法。如果有更好的方法,请发布我会接受它作为答案。