Skip to content

Commit

Permalink
Add file path validation
Browse files Browse the repository at this point in the history
  • Loading branch information
noibar committed Jun 27, 2018
1 parent f28cb45 commit f2fdb60
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
19 changes: 19 additions & 0 deletions baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"net"
"net/url"
"os"
"reflect"
"strconv"
"strings"
Expand Down Expand Up @@ -97,6 +98,7 @@ var (
"email": isEmail,
"url": isURL,
"uri": isURI,
"file": isFile,
"base64": isBase64,
"base64url": isBase64URL,
"contains": contains,
Expand Down Expand Up @@ -1060,6 +1062,23 @@ func isURL(fl FieldLevel) bool {
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}

// IsFile is the validation function for validating if the current field's value is a valid file path.
func isFile(fl FieldLevel) bool {
field := fl.Field()

switch field.Kind() {
case reflect.String:
fileInfo, err := os.Stat(field.String())
if err != nil {
return false
}

return !fileInfo.IsDir()
}

panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}

// IsEmail is the validation function for validating if the current field's value is a valid email address.
func isEmail(fl FieldLevel) bool {
return emailRegex.MatchString(fl.Field().String())
Expand Down
1 change: 1 addition & 0 deletions testdata/a.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package testdata
34 changes: 34 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"path/filepath"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -4446,6 +4447,39 @@ func TestBase64URLValidation(t *testing.T) {
}
}

func TestFileValidation(t *testing.T) {
validate := New()

tests := []struct {
title string
param string
expected bool
}{
{"empty path", "", false},
{"regular file", filepath.Join("testdata", "a.go"), true},
{"missing file", filepath.Join("testdata", "no.go"), false},
{"directory, not a file", "testdata", false},
}

for _, test := range tests {
errs := validate.Var(test.param, "file")

if test.expected {
if !IsEqual(errs, nil) {
t.Fatalf("Test: '%s' failed Error: %s", test.title, errs)
}
} else {
if IsEqual(errs, nil) {
t.Fatalf("Test: '%s' failed Error: %s", test.title, errs)
}
}
}

PanicMatches(t, func() {
validate.Var(6, "file")
}, "Bad field type int")
}

func TestEthereumAddressValidation(t *testing.T) {

validate := New()
Expand Down

0 comments on commit f2fdb60

Please sign in to comment.