Skip to content

treat values kind of string to allow regexp validation #15

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

Open
wants to merge 1 commit into
base: v2
Choose a base branch
from
Open
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
5 changes: 3 additions & 2 deletions builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,10 +197,11 @@ func max(v interface{}, param string) error {
// regex is the builtin validation function that checks
// whether the string variable matches a regular expression
func regex(v interface{}, param string) error {
s, ok := v.(string)
if !ok {
val := reflect.ValueOf(v)
if val.Kind() != reflect.String {
return ErrUnsupported
}
s := val.String()

re, err := regexp.Compile(param)
if err != nil {
Expand Down
22 changes: 21 additions & 1 deletion validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ package validator_test
import (
"testing"

"github.com/wcl48/go-validator"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm assuming you changed your imports for testing and forgot to change it back. Please do it and I'll merge.

. "gopkg.in/check.v1"
"gopkg.in/validator.v2"
)

func Test(t *testing.T) {
Expand Down Expand Up @@ -266,6 +266,26 @@ func (ms *MySuite) TestBadParameter(c *C) {
c.Assert(errs["C"], HasError, validator.ErrBadParameter)
}

func (ms *MySuite) TestExtendedTypes(c *C) {
type MyString string
type MyInt int
type MyFloat64 float64
type test struct {
A MyString `validate:"min=1,max=3,regexp=^[a-z]+$"`
B MyInt `validate:"min=0,max=100"`
C MyFloat64 `validate:"min=0,max=100"`
}

t1 := test{
A: MyString("abc"),
B: MyInt(100),
C: MyFloat64(99.999),
}

err := validator.Validate(t1)
c.Assert(err, IsNil)
}

type hasErrorChecker struct {
*CheckerInfo
}
Expand Down