英文:
Go validator.v2 gives error "unknown tag" for regexp
问题
我一直在努力理解为什么在使用golang中的validator.v2包时,一些正则表达式会给我一个"Unknown tag"的错误。它对一些正则表达式有效,但对一些包含"{}"的正则表达式无效,当我使用validator.Validate()时,它会在运行时给我一个"unknown tag"的错误。
以下是代码:
type Company struct {
Name string `validate:"regexp=^[a-zA-Z .]{1,100}$"`
}
这段代码在运行时给我以下错误:
Name: unknown tag
然而,这个正则表达式完全正常工作:
type Company struct {
Name string `validate:"regexp=^[a-zA-Z .]*$"`
}
我之所以使用大括号是因为我想对字符串设置长度限制。可能有其他方法可以实现,但我觉得正则表达式是一种更简单的方式,可以与其他规则一起放在表达式中。
英文:
I have been trying to understand why some regular expressions give me an error "Unknown tag" while using the validator.v2 package in golang. It works for some regular expressions but does not work with some which have "{}" inside them, and when I use the validator.Validate() it gives me an error at runtime "unknown tag".
Here's the code:
type Company struct {
Name string `validate:"regexp=^[a-zA-Z .]{1,100}$"`
}
which gives me the following error at runtime:
Name: unknown tag
however this regex works perfectly fine
type Company struct {
Name string `validate:"regexp=^[a-zA-Z .]*$"`
}
I am using the braces because of length restrictions that I want to put on the string. There could be other ways to do it, but I feel the regex is the way to go and is easier to have it along with other rules right there in the expression.
答案1
得分: 1
问题似乎出在你的第一个正则表达式中的逗号,
字符上。你可以在验证器的源代码中看到(https://github.com/go-validator/validator/blob/v2/validator.go#L332),标签是根据逗号,
进行分割的。通过查看源代码,我发现标签中没有对逗号进行转义的支持;这可能是项目作者的疏忽。我建议提交一个错误/功能请求。
英文:
The problem appears to be the ,
char in your first regex. You can see in the validator source code that the tag is split on ,
. By UTSLing, I see no support for escaped commas in the tags; this is probably an oversight on the part of the project author. I suggest filing a bug/feature request.
答案2
得分: 0
@Flimzy指出的问题是正确的,但这不是一个错误。
可能在那之后已经修复了,所以目前的validator
支持转义序列\\
来处理这种情况,你可以这样做:
type Company struct {
Name string `validate:"regexp=^[a-zA-Z .]{1\\,100}$"`
}
英文:
The problem pointed out by @Flimzy is correct, but it's not a bug.
Probably it was fixed since then, so at the moment validator
supports escape sequence \\
for such case, and you can do it like this:
type Company struct {
Name string `validate:"regexp=^[a-zA-Z .]{1\\,100}$"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论