validate.go

 1package text
 2
 3import (
 4	"net/url"
 5	"strings"
 6	"unicode"
 7)
 8
 9// Empty tell if the string is considered empty once space
10// and not graphics characters are removed
11func Empty(s string) bool {
12	trim := strings.TrimFunc(s, func(r rune) bool {
13		return unicode.IsSpace(r) || !unicode.IsGraphic(r)
14	})
15
16	return trim == ""
17}
18
19// Safe will tell if a character in the string is considered unsafe
20// Currently trigger on unicode control character except \n, \t and \r
21func Safe(s string) bool {
22	for _, r := range s {
23		switch r {
24		case '\t', '\r', '\n':
25			continue
26		}
27
28		if unicode.IsControl(r) {
29			return false
30		}
31	}
32
33	return true
34}
35
36// Safe will tell if a character in the string is considered unsafe
37// Currently trigger on all unicode control character
38func SafeOneLine(s string) bool {
39	for _, r := range s {
40		if unicode.IsControl(r) {
41			return false
42		}
43	}
44
45	return true
46}
47
48// ValidUrl will tell if the string contains what seems to be a valid URL
49func ValidUrl(s string) bool {
50	if strings.Contains(s, "\n") {
51		return false
52	}
53
54	_, err := url.ParseRequestURI(s)
55	return err == nil
56}