有没有像 Joi 这样的 JS 智能 json 模式验证器,但有动态自定义错误?

Is there any JS smart json schema validator, like Joi maybe, but with dynamic custom errors?

我想轻松地验证用户的输入。

当我询问用户的名字时(例如),可能需要大量代码行才能真正使它得到良好的验证。

我想要一些可以在前端和后端使用的东西 - 无需更改验证结构。

我需要能够抛出自定义详细错误,如下所示:

let schema = Joi.object.keys({
  first_name: Joi.string("Required to be a string")
  .noNumbers("Should not contain numbers")
  .minlenth(2, "At least 2 chars")
  .maxlength(10, "Maximum 10 chars")
  .required("Required field"),
  last_name: Joi.string("Required to be a string")
  .noNumbers("Should not contain numbers")
  .minlenth(2, "At least 2 chars")
  .maxlength(10, "Maximum 10 chars")
  .required("Required field"),
});

不幸的是,上面的方法不起作用 - 因为 Joi 不是这样工作的。

也许有一个很好的 JSON 模式验证器可以轻松有效地验证用户的输入而不浪费时间 - 同时让用户清楚?

您可以使用 JOI。在下面的示例中,我直接覆盖了错误:

   return Joi.object()
      .keys({
        str: Joi.string()
          .min(2)
          .max(10)
          .required()
          .error(errors => errors.map((err) => {
            const customMessage = ({
              'string.min': 'override min',
              'string.max': 'override max',
            })[err.type];

            if (customMessage) err.message = customMessage;

            return err;
          })),
      });

考虑到所有请求的错误消息都相同,我建议您使用一个函数:

function customErrors(errors) {
   return errors.map((err) => {
        const customMessage = ({
             'string.min': 'override min',
             'string.max': 'override max',
        })[err.type];

        if (customMessage) err.message = customMessage;

       return err;
   });
}

return Joi.object()
    .keys({
      str: Joi.string()
           .min(2)
           .max(10)
           .required()
           .error(customErrors),
      });

编辑:

// This

const customMessage = ({
  'string.min': 'override min',
  'string.max': 'override max',
})[err.type];

if (customMessage) err.message = customMessage;


// Equals this

let customMessage = false;

if (err.type === 'string.min') customMessage = 'override min';
if (err.type === 'string.max') customMessage = 'override max';

if (customMessage) err.message = customMessage;


// Equals this

if (err.type === 'string.min') err.message = 'override min';
if (err.type === 'string.max') err.message = 'override max';