Skip to content

Commit

Permalink
IsFilePath function
Browse files Browse the repository at this point in the history
  • Loading branch information
asaskevich committed Jan 15, 2015
1 parent 4fe067c commit 29b13e1
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
11 changes: 11 additions & 0 deletions patterns.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,18 @@ const (
Longitude string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
URL string = `^((ftp|http|https):\/\/)?(\S+(:\S*)?@)?((([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|((www\.)?)?(([a-z\x{00a1}-\x{ffff}0-9]+-?-?_?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-z\x{00a1}-\x{ffff}]{2,}))?)|localhost)(:(\d{1,5}))?((\/|\?|#)[^\s]*)?$`
SSN string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$`
WinPath string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$`
UnixPath string = `^((?:\/[a-zA-Z0-9\.\:]+(?:_[a-zA-Z0-9\:\.]+)*(?:\-[\:a-zA-Z0-9\.]+)*)+\/?)$`
tagName string = "valid"
)

const (
// Used by IsFilePath func
Unknown = iota
Win
Unix
)

var (
rxEmail = regexp.MustCompile(Email)
rxCreditCard = regexp.MustCompile(CreditCard)
Expand Down Expand Up @@ -60,4 +69,6 @@ var (
rxLongitude = regexp.MustCompile(Longitude)
rxURL = regexp.MustCompile(URL)
rxSSN = regexp.MustCompile(SSN)
rxWinPath = regexp.MustCompile(WinPath)
rxUnixPath = regexp.MustCompile(UnixPath)
)
9 changes: 9 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,15 @@ func IsBase64(str string) bool {
return rxBase64.MatchString(str)
}

func IsFilePath(str string) (bool, int) {
if rxWinPath.MatchString(str) {
return true, Win
} else if rxUnixPath.MatchString(str) {
return true, Unix
}
return false, Unknown
}

// IsDataURI checks if a string is base64 encoded data URI such as an image
func IsDataURI(str string) bool {
dataURI := strings.Split(str, ",")
Expand Down
26 changes: 26 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1404,6 +1404,32 @@ func TestIsMAC(t *testing.T) {
}
}

func TestFilePath(t *testing.T) {
t.Parallel()

var tests = []struct {
param string
expected bool
osType int
}{
{"c:\\path\\file", true, Win},
{"c:\\path\\file:exe", false, Unknown},
{"C:\\", true, Win},
{"c:\\path\\file\\", true, Win},
{"c:/path/file/", false, Unknown},
{"/path/file/", true, Unix},
{"/path/file:SAMPLE/", true, Unix},
{"/path/file:/.txt", true, Unix},
{"/path", true, Unix},
}
for _, test := range tests {
actual, osType := IsFilePath(test.param)
if actual != test.expected || osType != test.osType {
t.Errorf("Expected IsFilePath(%q) to be %v, got %v", test.param, test.expected, actual)
}
}
}

func TestIsLatitude(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 29b13e1

Please sign in to comment.