Skip to content

Commit

Permalink
fix file URL validator (#1171)
Browse files Browse the repository at this point in the history
## Fixes Or Enhances

This PR adds an additional check for the file URL schema.
Connected to #1165

**Make sure that you've checked the boxes below before you submit PR:**
- [x] Tests exist or have been written that cover this particular
change.

@go-playground/validator-maintainers
  • Loading branch information
nodivbyzero authored Nov 4, 2023
1 parent aa96909 commit c856961
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
15 changes: 14 additions & 1 deletion baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -1414,19 +1414,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 @@ -8139,6 +8139,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

0 comments on commit c856961

Please sign in to comment.