diff --git a/regex.go b/regex.go new file mode 100644 index 0000000..c262051 --- /dev/null +++ b/regex.go @@ -0,0 +1,19 @@ +package validator + +import "regexp" + +const ( + // Regex represents the rule name which will be used to find the default error message. + Regex = "regex" + // RegexMsg is the default error message format for fields with the regex validation rule. + RegexMsg = "%s is not valid" +) + +// RegexMatches checks the value of s under validation must match the given regular expression. +func (v *Validator) RegexMatches(s string, pattern string, field, msg string) *Validator { + r := regexp.MustCompile(pattern) + + v.Check(r.Match([]byte(s)), field, v.msg(Regex, msg)) + + return v +} diff --git a/regex_test.go b/regex_test.go new file mode 100644 index 0000000..4d39008 --- /dev/null +++ b/regex_test.go @@ -0,0 +1,77 @@ +package validator + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestValidator_RegexMatches(t *testing.T) { + tests := []struct { + name string + field string + value string + pattern string + isPassed bool + message string + expectedMsg string + }{ + { + name: "test an empty string value will fail regex validation", + field: "code", + value: "", + pattern: "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$", + isPassed: false, + message: "code is not valid", + expectedMsg: "code is not valid", + }, + { + name: "test an empty space string value will fail regex validation", + field: "name", + value: " ", + pattern: "^[0-9]{10}$", + isPassed: false, + message: "name is not valid", + expectedMsg: "name is not valid", + }, + { + name: "test a wrong string value will fail regex validation", + field: "id", + value: "09377475856", + pattern: "^[0-9]{10}$", + isPassed: false, + message: "id is not valid", + expectedMsg: "id is not valid", + }, + { + name: "test a correct string value will pass validation", + field: "id", + value: "1160277052", + pattern: "^[0-9]{10}$", + isPassed: true, + message: "", + expectedMsg: "", + }, + { + name: "test a correct email string value will pass validation", + field: "email", + value: "rezakhdemix@gmail.com", + pattern: "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$", + isPassed: true, + message: "", + expectedMsg: "", + }, + } + + for _, test := range tests { + v := New() + + v.RegexMatches(test.value, test.pattern, test.field, test.message) + + assert.Equal(t, test.isPassed, v.IsPassed()) + + if !test.isPassed { + assert.Equal(t, test.expectedMsg, v.Errors()[test.field]) + } + } +} diff --git a/validator.go b/validator.go index 4d6d11b..f3aac23 100644 --- a/validator.go +++ b/validator.go @@ -35,6 +35,7 @@ var ( Min: MinMsg, Between: BetweenMsg, NotExists: NotExistsMsg, + Regex: RegexMsg, } // ErrMethodMessageNotFound is the default message when a method does not have any error message on methodToErrorMessage.