87 lines
2.0 KiB
Go
Raw Normal View History

2019-06-03 09:32:43 +00:00
package validate
import (
"net/url"
"regexp"
"strings"
"time"
2019-11-17 06:45:02 +00:00
"unicode/utf8"
2019-06-03 09:32:43 +00:00
"github.com/animenotifier/notify.moe/arn/autocorrect"
)
const (
// DateFormat is the format used for short dates that don't include the time.
DateFormat = "2006-01-02"
// YearMonthFormat is the format used for validating dates that include the year and month.
YearMonthFormat = "2006-01"
2019-06-03 09:32:43 +00:00
// DateTimeFormat is the format used for long dates that include the time.
DateTimeFormat = time.RFC3339
)
var (
discordNickRegex = regexp.MustCompile(`^([^#]{2,32})#(\d{4})$`)
2019-10-21 05:02:09 +00:00
emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
2019-06-03 09:32:43 +00:00
)
// Nick tests if the given nickname is valid.
func Nick(nick string) bool {
if len(nick) < 2 {
return false
}
2019-11-17 06:45:02 +00:00
if !utf8.ValidString(nick) {
return false
}
2019-06-03 09:32:43 +00:00
return nick == autocorrect.UserNick(nick)
}
// DiscordNick tests if the given Discord nickname is valid.
func DiscordNick(nick string) bool {
return discordNickRegex.MatchString(nick)
}
// DateTime tells you whether the datetime is valid.
func DateTime(date string) bool {
if date == "" || strings.HasPrefix(date, "0001") {
return false
}
_, err := time.Parse(DateTimeFormat, date)
return err == nil
}
// Date tells you whether the datetime is valid.
func Date(date string) bool {
if date == "" || strings.HasPrefix(date, "0001") {
return false
}
_, err := time.Parse(DateFormat, date)
return err == nil
}
2019-09-05 23:24:08 +00:00
// YearMonth tells you whether the date contains only the year and the month.
func YearMonth(date string) bool {
if len(date) != len(YearMonthFormat) || strings.HasPrefix(date, "0001") {
return false
}
_, err := time.Parse(YearMonthFormat, date)
return err == nil
}
2019-06-03 09:32:43 +00:00
// Email tests if the given email address is valid.
func Email(email string) bool {
2019-10-21 05:02:09 +00:00
return emailRegex.MatchString(email)
2019-06-03 09:32:43 +00:00
}
// URI validates a URI.
func URI(uri string) bool {
_, err := url.ParseRequestURI(uri)
return err == nil
}