Skip to content

Commit c856961

Browse files
authored
fix file URL validator (#1171)
## 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
1 parent aa96909 commit c856961

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

baked_in.go

+14-1
Original file line numberDiff line numberDiff line change
@@ -1414,19 +1414,32 @@ func isURI(fl FieldLevel) bool {
14141414
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
14151415
}
14161416

1417+
// isFileURL is the helper function for validating if the `path` valid file URL as per RFC8089
1418+
func isFileURL(path string) bool {
1419+
if !strings.HasPrefix(path, "file:/") {
1420+
return false
1421+
}
1422+
_, err := url.ParseRequestURI(path)
1423+
return err == nil
1424+
}
1425+
14171426
// isURL is the validation function for validating if the current field's value is a valid URL.
14181427
func isURL(fl FieldLevel) bool {
14191428
field := fl.Field()
14201429

14211430
switch field.Kind() {
14221431
case reflect.String:
14231432

1424-
s := field.String()
1433+
s := strings.ToLower(field.String())
14251434

14261435
if len(s) == 0 {
14271436
return false
14281437
}
14291438

1439+
if isFileURL(s) {
1440+
return true
1441+
}
1442+
14301443
url, err := url.Parse(s)
14311444
if err != nil || url.Scheme == "" {
14321445
return false

validator_test.go

+6
Original file line numberDiff line numberDiff line change
@@ -8139,6 +8139,12 @@ func TestUrl(t *testing.T) {
81398139
{"./rel/test/dir", false},
81408140
{"irc:", false},
81418141
{"http://", false},
8142+
{"file://path/to/file.txt", true},
8143+
{"file:///c:/Windows/file.txt", true},
8144+
{"file://localhost/path/to/file.txt", true},
8145+
{"file://localhost/c:/WINDOWS/file.txt", true},
8146+
{"file://", true},
8147+
{"file:////remotehost/path/file.txt", true},
81428148
}
81438149

81448150
validate := New()

0 commit comments

Comments
 (0)