piekarnikgosipl/orders/field_validations.go
2026-11-09 16:29:52 +01:00

85 lines
1.8 KiB
Go

package orders
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
"unicode"
)
func isValidPolishMobile(nineDigitNum string) bool {
if len(nineDigitNum) != 9 {
return false
}
firstDigit := nineDigitNum[0]
if firstDigit < '4' || firstDigit > '8' {
return false
}
prefix2 := nineDigitNum[:2]
validPrefixes := map[string]bool{
"45": true,
"50": true, "51": true, "53": true, "57": true,
"60": true, "66": true, "69": true,
"72": true, "73": true, "78": true, "79": true,
"88": true,
}
return validPrefixes[prefix2]
}
func parsePhone(input string) (string, error) {
input = strings.TrimSpace(input)
if strings.HasPrefix(input, "+48") {
input = strings.TrimPrefix(input, "+48")
} else if strings.HasPrefix(input, "0048") {
input = strings.TrimPrefix(input, "0048")
}
re := regexp.MustCompile(`\D`)
cleaned := re.ReplaceAllString(input, "")
if len(cleaned) == 11 && strings.HasPrefix(cleaned, "48") {
cleaned = cleaned[2:]
}
if len(cleaned) != 9 {
return "", fmt.Errorf("Numer telefonu musi mieć 9 cyfr")
}
if !isValidPolishMobile(cleaned) {
return "", fmt.Errorf("Nieprawidłowy numer telefonu — podaj polski numer komórkowy")
}
return cleaned, nil
}
func parseFloat(input string) (int, error) {
val, err := strconv.ParseFloat(input, 64)
if err != nil {
return 0, fmt.Errorf("Nieprawidłowa wartość")
}
if val < 0 || val > 100 {
return 0, fmt.Errorf("Wartość musi być między 0 a 100")
}
doubled := val * 2
if math.Abs(doubled-math.Round(doubled)) > 1e-9 {
return 0, fmt.Errorf("Wartość musi być wielokrotnością 0,5")
}
return int(math.Round(val * 10)), nil
}
func validName(name string) bool {
if name == "" || len(name) > 100 {
return false
}
return strings.IndexFunc(name, unicode.IsControl) == -1
}