如何在 joi 中为正则表达式设置自定义消息

编程入门 行业动态 更新时间:2024-10-26 12:22:46
本文介绍了如何在 joi 中为正则表达式设置自定义消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我验证我的 graphql 参数时,我收到密码字段的错误消息.

When I validate my graphql arguments, I'm getting error message like this for the password field.

"password" with value "" fails to match the required pattern: /^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,30}$/"

我不想在错误消息中显示正则表达式模式.所以我尝试为密码字段设置自定义错误消息,但它仍然显示正则表达式模式.

I don't want to show regex pattern in the error message. So I tried to set the custom error message for the password field but still it's showing the regex pattern.

import Joi from "joi";

export default Joi.object().keys({
  email: Joi.string().email().required().label("Email"),
  username: Joi.string().alphanum().min(4).max(20).required().label("Username"),
  name: Joi.string().min(4).max(256).required().label("Name"),
  password: Joi.string()
    .min(8)
    .regex(/^(?=S*[a-z])(?=S*[A-Z])(?=S*d)(?=S*[^ws])S{8,30}$/)
    .required()
    .label("Password")
    .messages({
      "string.min": "Must have at least 8 characters",
      "object.regex": "Must have at least 8 characters",
    }),
});

我认为它不是通过 object.regex 选择正则表达式.请帮忙.

I think it's not selecting the regex by object.regex. Please help.

推荐答案

要知道抛出了什么错误,可以调试错误对象(通过记录),然后找到type错误.

To know what error is being thrown, you can debug the error object (by logging it), and then finding the type of error.

示例:

const Joi = require('@hapi/joi');

const joiSchema = Joi.object().keys({
  password: Joi.string()
    .min(8)
    .regex(/^(?=S*[a-z])(?=S*[A-Z])(?=S*d)(?=S*[^ws])S{8,30}$/)
    .required()
    .label("Password")
    .messages({
      "string.min": "Must have at least 8 characters",
      "object.regex": "Must have at least 8 characters",
      "string.pattern.base": "enter your custom error here..."
    })
});

const validationResult = joiSchema.validate({ password: "2" }, { abortEarly: false });
console.log(validationResult.error.details.map(errDetail => errDetail.type), validationResult.error);

这会输出 [string.min", string.pattern.base"].details 由于 string.min 和 string.pattern.base 有 2 个错误,并且 abortEarly 设置为 false.

This outputs ["string.min", "string.pattern.base"]. details has 2 errors because of string.min and string.pattern.base, and abortEarly is set to false.

这篇关于如何在 joi 中为正则表达式设置自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 01:45:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/674921.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   中为   消息   如何在   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!