Merge pull request #375 from noibar/add_file_validation

Add file path validation
pull/380/head
Dean Karn 7 years ago committed by GitHub
commit 71510749b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 19
      baked_in.go
  2. 1
      testdata/a.go
  3. 34
      validator_test.go

@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"net" "net"
"net/url" "net/url"
"os"
"reflect" "reflect"
"strconv" "strconv"
"strings" "strings"
@ -97,6 +98,7 @@ var (
"email": isEmail, "email": isEmail,
"url": isURL, "url": isURL,
"uri": isURI, "uri": isURI,
"file": isFile,
"base64": isBase64, "base64": isBase64,
"base64url": isBase64URL, "base64url": isBase64URL,
"contains": contains, "contains": contains,
@ -1060,6 +1062,23 @@ func isURL(fl FieldLevel) bool {
panic(fmt.Sprintf("Bad field type %T", field.Interface())) 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. // IsEmail is the validation function for validating if the current field's value is a valid email address.
func isEmail(fl FieldLevel) bool { func isEmail(fl FieldLevel) bool {
return emailRegex.MatchString(fl.Field().String()) return emailRegex.MatchString(fl.Field().String())

1
testdata/a.go vendored

@ -0,0 +1 @@
package testdata

@ -8,6 +8,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"path/filepath"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
@ -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) { func TestEthereumAddressValidation(t *testing.T) {
validate := New() validate := New()

Loading…
Cancel
Save