我目前正在使用 Go Validator.v2 ( https://godoc.org/gopkg.in/validator.v2 ) 通过内置的正则表达式功能执行一些数据验证。给出的简单示例适合我:
type NewUserRequest struct {
SomeString string `validate:"min=3,max=40,regexp=^[a-zA-Z0-9]*$"`
}
nur := NewUserRequest{SomeString : "JamesBond"}
但是,当我开始向 RegEx 引入复杂性时,例如允许需要转义(用于验证电子邮件或其他内容)的多个特殊字符( _
或 -
或 .
),我开始遇到问题。如果我用双斜杠转义特殊字符,我要么得到“未知标签”错误 \\
否则,如果我使用单斜杠 \
,它将简单地跳过验证(任何字符串都将通过) :Input string: "James.Bond-007@email.co.uk"
regexp: `validate:"regexp=^[_A-Za-z0-9\\-\\+]+(\\.[_A-Za-z0-9\\-]+)*@[A-Za-z0-9\\-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"`
Expected result: PASS - valid string
Actual result/output: 'Unknown tag' error
Input string: "06/06/2006"
regexp: `validate:"regexp=^[_A-Za-z0-9\-\+]+(\.[_A-Za-z0-9\-]+)*@[A-Za-z0-9\-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$"`
Expected result: Invalid string
Actual result/output: PASS - Validation passed/skipped.
任何其他有类似问题的人,或者可以提供一种使用 Go Validator.v2 正确转义正则表达式的方法吗?任何指针将不胜感激。先感谢您!
最佳答案
见 go-validator/validator
"Escape commas in regex" bug description :
You'll need to escape the comma with 2 backslashes.
你可以像这样修复你的代码:
regexp: `validate:"regexp=^[_A-Za-z0-9+-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2\\,})$"`
请注意,当连字符位于字符类中的最终位置时,您不需要对其进行转义,并且 +
不必在那里逃脱。
关于regex - 使用 Go Validator v2 转义正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64358728/