Skip to content

Commit

Permalink
validator
Browse files Browse the repository at this point in the history
  • Loading branch information
iesreza committed Mar 15, 2024
1 parent 2d6a20d commit d496217
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ func TestStruct(t *testing.T) {
AlphaNumeric: "a1",
Email: "reza+5@yahoo.com",
RequiredEmail: "reza+5@yahoo.com",
URL: "https://example.com",
URL: "https://example.com/path",
Domain: "example.com",
IP: "127.0.0.1",
IP: "127.0.1.5",
Regex: "ab~",
LengthEq: "1234567890",
LengthGt: "1234567890001",
Expand Down
52 changes: 52 additions & 0 deletions lib/validation/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package validation
import (
"fmt"
"github.com/getevo/evo/v2/lib/generic"
"net/url"
"regexp"
"strconv"
"strings"
Expand All @@ -20,6 +21,57 @@ var Validators = map[*regexp.Regexp]func(match []string, value *generic.Value) e
regexp.MustCompile(`^([+\-]?)int$`): intValidator,
regexp.MustCompile(`^([+\-]?)float$`): floatValidator,
regexp.MustCompile(`^password\((.*)\)$`): passwordValidator,
regexp.MustCompile(`^domain$`): domainValidator,
regexp.MustCompile(`^url$`): urlValidator,
regexp.MustCompile(`^ip$`): ipValidator,
}

func ipValidator(match []string, value *generic.Value) error {
var v = value.String()
if v == "" {
return nil
}
parts := strings.Split(v, ".")

if len(parts) != 4 {
return fmt.Errorf("invalid IP address: %s", v)
}

for _, x := range parts {
if i, err := strconv.Atoi(x); err == nil {
if i < 0 || i > 255 {
return fmt.Errorf("invalid IP address: %s", v)
}
} else {
return fmt.Errorf("invalid IP address: %s", v)
}

}
return nil
}

func urlValidator(match []string, value *generic.Value) error {
var v = value.String()
if v == "" {
return nil
}
_, err := url.ParseRequestURI(v)
if err != nil {
return err
}
return nil
}

func domainValidator(match []string, value *generic.Value) error {
var v = value.String()
if v == "" {
return nil
}
var regex = regexp.MustCompile(`(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]`)
if !regex.MatchString(v) {
return fmt.Errorf("invalid domain: %s", v)
}
return nil
}

func passwordValidator(match []string, value *generic.Value) error {
Expand Down

0 comments on commit d496217

Please sign in to comment.