Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping regex expressions using Go Validator v2

I'm currently using Go Validator.v2 (https://godoc.org/gopkg.in/validator.v2) to perform some data validation via the in-built regexp feature. The simple example given works correctly for me:

type NewUserRequest struct {
    SomeString string `validate:"min=3,max=40,regexp=^[a-zA-Z0-9]*$"`
}
nur := NewUserRequest{SomeString : "JamesBond"}

However, when I start to introduce complexity to the RegEx such as allowing multiple special characters (_ or - or .) which require escaping (for validating an email or something), I start to encounter issues. I either get an "Unknown tag" error if I escape special characters with double slash\\ or it will simply skip validation (any string will pass) if I use single slash \:

Input string: "[email protected]"
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.

Anyone else having similar issues or can provide a way to escape regexp correctly using Go Validator.v2?

Any pointers would be much appreciated. Thank you in advance!

like image 517
DevO Avatar asked Apr 10 '26 03:04

DevO


1 Answers

See the go-validator/validator "Escape commas in regex" bug description:

You'll need to escape the comma with 2 backslashes.

You can fix your code like this:

regexp: `validate:"regexp=^[_A-Za-z0-9+-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2\\,})$"`

Note you do not need to escape a hyphen when it is at the final position inside a character class, and + does not have to be escaped there.

like image 161
Wiktor Stribiżew Avatar answered Apr 12 '26 17:04

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!