utils/validators.go

86 lines
2.2 KiB
Go
Raw Permalink Normal View History

2023-10-02 23:42:16 +02:00
package utils
2023-10-13 20:38:08 +02:00
import (
"net/url"
"os"
2024-06-05 21:32:49 +02:00
"regexp"
2023-11-03 20:43:13 +01:00
"github.com/google/uuid"
2023-10-13 20:38:08 +02:00
)
// DoesFileExist returns true, if a file exists (and actually is a file)
func DoesFileExist(p string) bool {
s, err := os.Stat(p)
if os.IsNotExist(err) {
return false
}
if s.IsDir() {
return false
}
return true
}
// DoesFolderExist returns true, if a folder exists (and actually is a folder)
func DoesFolderExist(p string) bool {
s, err := os.Stat(p)
if os.IsNotExist(err) {
return false
}
if !s.IsDir() {
return false
}
return true
}
// DoesStringContainsNonWhitelistedSubstrings returns false if s contains substrings which are not in whitelist
func DoesStringContainsNonWhitelistedSubstrings(s string, whitelist map[string]string) bool {
for _, char := range s {
_, charIsWhitelisted := whitelist[string(char)]
if !charIsWhitelisted {
return true
}
}
return false
}
2023-10-02 23:42:16 +02:00
// IsStringInSliceOfStrings returns true, if slice contains target
func IsStringInSliceOfStrings(slice []string, target string) bool {
for _, v := range slice {
if v == target {
return true
}
}
return false
}
2024-06-05 21:32:49 +02:00
// IsValidEmail returns true, if s is a email address.
func IsValidEmail(s string) bool {
// Used Regex instead of mail.ParseAddress(), as the latter incorrectly recognizes samples such as “bad@domain” as a valid address
// Shoutout to emailregex.com for the almighty regular expression
return regexp.MustCompile(
`(?:[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])`,
).MatchString(s)
}
2023-11-03 20:43:13 +01:00
// IsValidURL returns true, if s is a valid URL
func IsValidURL(s string) bool {
2023-10-02 23:42:16 +02:00
u, err := url.Parse(s)
if err != nil || u.Scheme == "" || u.Host == "" {
return false
}
return true
}
2023-11-03 20:43:13 +01:00
// IsValidUUID returns true, if s is a valid UUID
func IsValidUUID(s string) bool {
_, err := uuid.Parse(s)
return err == nil
}