-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
48 lines (39 loc) · 1.03 KB
/
validate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* Ali Ahmadi
* Dedicated to MHM
*/
package num2text
import (
"fmt"
"strings"
)
func existInArray[T comparable](value T, values []T) bool {
for _, v := range values {
if v == value {
return true
}
}
return false
}
func numberValidator(num string) (bool, error) {
// number can not be just a '-', '.' or ''
iv := []string{"-", ".", ""}
if existInArray(num, iv) {
return false, fmt.Errorf("number can not be %+v", iv)
}
// check all characters of input number to be in valid chars
validchs := strings.Split("-.0123456789", "")
for _, v := range strings.Split(num, "") {
if !existInArray(v, validchs) {
return false, fmt.Errorf("%s contain invalid characters", num)
}
}
// number can not have more that one '-' or '.'
if strings.Count(num, "-") > 1 || strings.Count(num, ".") > 1 {
return false, fmt.Errorf("number can not have more that one '-' or '.'")
}
if strings.Count(num, "-") == 1 && strings.Index(num, "-") != 0 {
return false, fmt.Errorf("'-' character should be in 0 index")
}
return true, nil
}