Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IsRegex function added! (issue#155) #434

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,18 @@ func IsUTFLetterNumeric(str string) bool {

}

// IsRegex checks if the string is a valid regex. Empty string is valid.
func IsRegex(str string) bool {
if IsNull(str) {
return true
}
_, err := regexp.Compile(str)
if err != nil {
return false
}
return true
}

// IsNumeric checks if the string contains only numbers. Empty string is valid.
func IsNumeric(str string) bool {
if IsNull(str) {
Expand Down
26 changes: 26 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,32 @@ func TestIsLowerCase(t *testing.T) {
}
}

func TestIsRegex(t *testing.T) {
t.Parallel()

var tests = []struct {
param string
expected bool
}{
{"", true},
{"p([a-z]+)ch", true},
{"//", true},
{"/[0-9]+/", true},
{"^a.b$", true},
{"[", false},
{"*", false},
{"+*^", false},
{"[0-9]++", false},
{"[)", false},
}
for _, test := range tests {
actual := IsRegex(test.param)
if actual != test.expected {
t.Errorf("Expected IsRegex(%q) to be %v, got %v", test.param, test.expected, actual)
}
}
}

func TestIsUpperCase(t *testing.T) {
t.Parallel()

Expand Down