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

fix file URL validator #1171

Merged
merged 1 commit into from
Nov 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 14 additions & 1 deletion baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -1413,19 +1413,32 @@ func isURI(fl FieldLevel) bool {
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}

// isFileURL is the helper function for validating if the `path` valid file URL as per RFC8089
func isFileURL(path string) bool {
if !strings.HasPrefix(path, "file:/") {
return false
}
_, err := url.ParseRequestURI(path)
return err == nil
}

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

switch field.Kind() {
case reflect.String:

s := field.String()
s := strings.ToLower(field.String())

if len(s) == 0 {
return false
}

if isFileURL(s) {
return true
}

url, err := url.Parse(s)
if err != nil || url.Scheme == "" {
return false
Expand Down
6 changes: 6 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8090,6 +8090,12 @@ func TestUrl(t *testing.T) {
{"./rel/test/dir", false},
{"irc:", false},
{"http://", false},
{"file://path/to/file.txt", true},
{"file:///c:/Windows/file.txt", true},
{"file://localhost/path/to/file.txt", true},
{"file://localhost/c:/WINDOWS/file.txt", true},
{"file://", true},
{"file:////remotehost/path/file.txt", true},
}

validate := New()
Expand Down