验证器,使用golang的请求中仅包含英文字母和标点符号

问题描述 投票:0回答:1

我正在使用 Golang 构建我的第一个 Web 服务。 我想要一个验证器来检查属性是否只有英文字母和标点符号。 我发现验证“github.com/astaxie/beego/validation”包非常简单和方便,我决定使用 Match 验证器和以下正则表达式,如下所示:

type ParagraphRequest struct {
// Regular expression to match only English letters, punctuation, and spaces
Paragraph string `json:"paragraph" valid:"Required;Match(/^[a-zA-Z\s.,!?;:'\"()\-]+$/);MaxSize(1000)"`
}

但是由于某种原因,当我用其他语言的信件发送请求时,检查会忽略它并且不会引发任何错误:

// BindAndValid binds and validates data
func BindAndValid(c *gin.Context, request interface{}) int {
    err := c.Bind(request)
    if err != nil {
        return http.StatusBadRequest
    }

valid := validation.Validation{}
check, err := valid.Valid(request)
if err != nil {
    return http.StatusInternalServerError
}
if !check {
    MarkErrors(valid.Errors)
    return http.StatusBadRequest
}

return http.StatusOK
}

我错过了什么?我使用

regexp.MustCompile
检查了正则表达式,效果很好。

我对替代方案持开放态度(beego 除外)。

regex go validation beego
1个回答
0
投票

如果您只想在正则表达式中允许使用 unicode,则需要使用这些:

  • \p{L}:匹配任何 Unicode 字母,其中包括非英语字符。
  • \p{N}:匹配任何 Unicode 数字(数字)。
  • \p{P}:匹配标点符号。
  • \p{Z}:匹配空格和其他分隔符。

我认为你需要将正则表达式更改为:

/^[\p{L}\s.,!?;:'"()\u002D]+$/

这里 \u002D 是 unicode hiphen

© www.soinside.com 2019 - 2024. All rights reserved.