gf/util/gvalid/gvalid_check.go

449 lines
12 KiB
Go
Raw Normal View History

// Copyright 2017-2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gvalid
import (
2019-07-29 21:01:19 +08:00
"github.com/gogf/gf/encoding/gjson"
"github.com/gogf/gf/net/gipv4"
"github.com/gogf/gf/net/gipv6"
"github.com/gogf/gf/os/gtime"
"github.com/gogf/gf/text/gregex"
"github.com/gogf/gf/util/gconv"
"regexp"
"strconv"
"strings"
)
const (
2020-05-10 10:56:11 +08:00
// regular expression pattern for single validation rule.
gSINGLE_RULE_PATTERN = `^([\w-]+):{0,1}(.*)`
)
var (
2020-05-10 10:56:11 +08:00
// regular expression object for single rule
// which is compiled just once and of repeatable usage.
2019-06-19 09:06:52 +08:00
ruleRegex, _ = regexp.Compile(gSINGLE_RULE_PATTERN)
2020-05-10 10:56:11 +08:00
// mustCheckRulesEvenValueEmpty specifies some rules that must be validated
// even the value is empty (nil or empty).
2019-06-19 09:06:52 +08:00
mustCheckRulesEvenValueEmpty = map[string]struct{}{
2019-09-13 22:08:18 +08:00
"required": {},
"required-if": {},
"required-unless": {},
"required-with": {},
"required-with-all": {},
"required-without": {},
"required-without-all": {},
"same": {},
"different": {},
"in": {},
"not-in": {},
"regex": {},
2019-06-19 09:06:52 +08:00
}
2020-05-10 10:56:11 +08:00
// allSupportedRules defines all supported rules that is used for quick checks.
2019-06-19 09:06:52 +08:00
allSupportedRules = map[string]struct{}{
2019-09-13 22:08:18 +08:00
"required": {},
"required-if": {},
"required-unless": {},
"required-with": {},
"required-with-all": {},
"required-without": {},
"required-without-all": {},
"date": {},
"date-format": {},
"email": {},
"phone": {},
"telephone": {},
"passport": {},
"password": {},
"password2": {},
"password3": {},
"postcode": {},
2020-05-10 10:56:11 +08:00
"resident-id": {},
"bank-card": {},
2019-09-13 22:08:18 +08:00
"qq": {},
"ip": {},
"ipv4": {},
"ipv6": {},
"mac": {},
"url": {},
"domain": {},
"length": {},
"min-length": {},
"max-length": {},
"between": {},
"min": {},
"max": {},
"json": {},
"integer": {},
"float": {},
"boolean": {},
"same": {},
"different": {},
"in": {},
"not-in": {},
"regex": {},
2019-06-19 09:06:52 +08:00
}
2020-05-10 10:56:11 +08:00
// boolMap defines the boolean values.
2019-06-19 09:06:52 +08:00
boolMap = map[string]struct{}{
2019-09-13 22:08:18 +08:00
"1": {},
"true": {},
"on": {},
"yes": {},
"": {},
"0": {},
"false": {},
"off": {},
"no": {},
2019-06-19 09:06:52 +08:00
}
)
2020-05-10 16:48:00 +08:00
// Check checks single value with specified rules.
2020-05-10 17:49:23 +08:00
// It returns nil if with successful validation.
2019-03-06 10:38:50 +08:00
//
2020-05-10 16:48:00 +08:00
// The parameter <value> can be any type of variable, which will be converted to string
// for validation.
// The parameter <rules> can be one or more rules, multiple rules joined using char '|'.
// The parameter <messages> specifies the custom error messages, which can be type of:
// string/map/struct/*struct.
// The optional parameter <params> specifies the extra validation parameters for some rules
// like: required-*、same、different, etc.
func Check(value interface{}, rules string, messages interface{}, params ...interface{}) *Error {
if rules == "" {
return nil
}
2020-05-10 16:48:00 +08:00
// It converts value to string and then does the validation.
var (
val = strings.TrimSpace(gconv.String(value))
data = make(map[string]string)
errorMsgs = make(map[string]string)
)
2019-06-19 09:06:52 +08:00
if len(params) > 0 {
for k, v := range gconv.Map(params[0]) {
data[k] = gconv.String(v)
}
}
2020-05-10 16:48:00 +08:00
// Custom error messages handling.
var (
msgArray = make([]string, 0)
customMsgMap = make(map[string]string)
)
switch v := messages.(type) {
2019-06-19 09:06:52 +08:00
case string:
msgArray = strings.Split(v, "|")
default:
2020-05-10 16:48:00 +08:00
for k, v := range gconv.Map(messages) {
2019-06-19 09:06:52 +08:00
customMsgMap[k] = gconv.String(v)
}
}
2020-05-10 16:48:00 +08:00
// Handle the char '|' in the rule,
// which makes this rule separated into multiple rules.
2019-06-19 09:06:52 +08:00
ruleItems := strings.Split(strings.TrimSpace(rules), "|")
for i := 0; ; {
array := strings.Split(ruleItems[i], ":")
if _, ok := allSupportedRules[array[0]]; !ok {
2019-07-12 21:37:48 +08:00
if i > 0 && ruleItems[i-1][:5] == "regex" {
2019-06-19 09:06:52 +08:00
ruleItems[i-1] += "|" + ruleItems[i]
ruleItems = append(ruleItems[:i], ruleItems[i+1:]...)
} else {
2020-05-10 16:48:00 +08:00
return newErrorStr(
"invalid_rules",
"invalid rules: "+rules,
)
2019-06-19 09:06:52 +08:00
}
} else {
i++
}
if i == len(ruleItems) {
break
}
}
for index := 0; index < len(ruleItems); {
2020-05-10 10:56:11 +08:00
var (
item = ruleItems[index]
match = false
results = ruleRegex.FindStringSubmatch(item)
ruleKey = strings.TrimSpace(results[1])
ruleVal = strings.TrimSpace(results[2])
)
2019-06-19 09:06:52 +08:00
if len(msgArray) > index {
customMsgMap[ruleKey] = strings.TrimSpace(msgArray[index])
}
switch ruleKey {
2020-05-10 10:56:11 +08:00
// Required rules.
case
"required",
"required-if",
"required-unless",
"required-with",
"required-with-all",
"required-without",
"required-without-all":
2019-06-19 09:06:52 +08:00
match = checkRequired(val, ruleKey, ruleVal, data)
2020-05-10 10:56:11 +08:00
// Length rules.
2020-05-10 16:48:00 +08:00
// It also supports length of unicode string.
2020-05-10 10:56:11 +08:00
case
"length",
"min-length",
"max-length":
2019-06-19 09:06:52 +08:00
if msg := checkLength(val, ruleKey, ruleVal, customMsgMap); msg != "" {
errorMsgs[ruleKey] = msg
} else {
match = true
}
2020-05-10 10:56:11 +08:00
// Range rules.
case
"min",
"max",
"between":
if msg := checkRange(val, ruleKey, ruleVal, customMsgMap); msg != "" {
2019-06-19 09:06:52 +08:00
errorMsgs[ruleKey] = msg
} else {
match = true
}
2020-05-10 10:56:11 +08:00
// Custom regular expression.
2019-06-19 09:06:52 +08:00
case "regex":
2020-05-10 10:56:11 +08:00
// It here should check the rule as there might be special char '|' in it.
2019-06-19 09:06:52 +08:00
for i := index + 1; i < len(ruleItems); i++ {
if !gregex.IsMatchString(gSINGLE_RULE_PATTERN, ruleItems[i]) {
ruleVal += "|" + ruleItems[i]
index++
}
}
match = gregex.IsMatchString(ruleVal, val)
2020-05-10 10:56:11 +08:00
// Date rules.
2019-06-19 09:06:52 +08:00
case "date":
2020-05-10 16:48:00 +08:00
// Standard date string, which must contain char '-' or '.'.
2019-06-19 09:06:52 +08:00
if _, err := gtime.StrToTime(val); err == nil {
match = true
break
}
2020-05-10 16:48:00 +08:00
// Date that not contains char '-' or '.'.
2019-06-19 09:06:52 +08:00
if _, err := gtime.StrToTime(val, "Ymd"); err == nil {
match = true
break
}
2020-05-10 10:56:11 +08:00
// Date rule with specified format.
2019-06-19 09:06:52 +08:00
case "date-format":
if _, err := gtime.StrToTimeFormat(val, ruleVal); err == nil {
match = true
}
2020-05-10 10:56:11 +08:00
// Values of two fields should be equal as string.
2019-06-19 09:06:52 +08:00
case "same":
if v, ok := data[ruleVal]; ok {
if strings.Compare(val, v) == 0 {
match = true
}
}
2020-05-10 10:56:11 +08:00
// Values of two fields should not be equal as string.
2019-06-19 09:06:52 +08:00
case "different":
match = true
if v, ok := data[ruleVal]; ok {
if strings.Compare(val, v) == 0 {
match = false
}
}
2020-05-10 10:56:11 +08:00
// Field value should be in range of.
2019-06-19 09:06:52 +08:00
case "in":
array := strings.Split(ruleVal, ",")
for _, v := range array {
if strings.Compare(val, strings.TrimSpace(v)) == 0 {
match = true
break
}
}
2020-05-10 10:56:11 +08:00
// Field value should not be in range of.
2019-06-19 09:06:52 +08:00
case "not-in":
match = true
array := strings.Split(ruleVal, ",")
for _, v := range array {
if strings.Compare(val, strings.TrimSpace(v)) == 0 {
match = false
break
}
}
2020-05-10 10:56:11 +08:00
// Phone format validation.
// 1. China Mobile:
// 134, 135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159, 182, 183, 184, 187, 188,
// 178(4G), 147(Net)
//
// 2. China Unicom:
// 130, 131, 132, 155, 156, 185, 186 ,176(4G), 145(Net), 175
//
// 3. China Telecom:
// 133, 153, 180, 181, 189, 177(4G)
//
// 4. Satelite:
// 1349
//
// 5. Virtual:
// 170, 173
//
// 6. 2018:
// 16x, 19x
2019-06-19 09:06:52 +08:00
case "phone":
match = gregex.IsMatchString(`^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^16[\d]{9}$|^17[0,3,5,6,7,8]{1}\d{8}$|^18[\d]{9}$|^19[\d]{9}$`, val)
2020-05-10 10:56:11 +08:00
// Telephone number:
// "XXXX-XXXXXXX"
// "XXXX-XXXXXXXX"
// "XXX-XXXXXXX"
// "XXX-XXXXXXXX"
// "XXXXXXX"
// "XXXXXXXX"
2019-06-19 09:06:52 +08:00
case "telephone":
match = gregex.IsMatchString(`^((\d{3,4})|\d{3,4}-)?\d{7,8}$`, val)
2020-05-10 10:56:11 +08:00
// QQ number: from 10000.
2019-06-19 09:06:52 +08:00
case "qq":
match = gregex.IsMatchString(`^[1-9][0-9]{4,}$`, val)
2020-05-10 10:56:11 +08:00
// Postcode number.
2019-06-19 09:06:52 +08:00
case "postcode":
match = gregex.IsMatchString(`^\d{6}$`, val)
2020-05-10 10:56:11 +08:00
// China resident id number.
//
// xxxxxx yyyy MM dd 375 0 十八位
// xxxxxx yy MM dd 75 0 十五位
//
// 地区: [1-9]\d{5}
// 年的前两位:(18|19|([23]\d)) 1800-2399
// 年的后两位:\d{2}
// 月份: ((0[1-9])|(10|11|12))
// 天数: (([0-2][1-9])|10|20|30|31) 闰年不能禁止29+
//
// 三位顺序码:\d{3}
// 两位顺序码:\d{2}
// 校验码: [0-9Xx]
//
// 十八位:^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$
// 十五位:^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$
//
// 总:
// (^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)
case "resident-id":
match = checkResidentId(val)
// Bank card number using LUHN algorithm.
2020-05-10 16:48:00 +08:00
case "bank-card":
match = checkLuHn(val)
2019-06-19 09:06:52 +08:00
2020-05-10 10:56:11 +08:00
// Universal passport format rule:
2020-05-10 16:48:00 +08:00
// Starting with letter, containing only numbers or underscores, length between 6 and 18.
2019-06-19 09:06:52 +08:00
case "passport":
match = gregex.IsMatchString(`^[a-zA-Z]{1}\w{5,17}$`, val)
2020-05-10 10:56:11 +08:00
// Universal password format rule1:
2020-05-10 16:48:00 +08:00
// Containing any visible chars, length between 6 and 18.
2019-06-19 09:06:52 +08:00
case "password":
match = gregex.IsMatchString(`^[\w\S]{6,18}$`, val)
2020-05-10 10:56:11 +08:00
// Universal password format rule2:
// Must meet password rule1, must contain lower and upper letters and numbers.
2019-06-19 09:06:52 +08:00
case "password2":
if gregex.IsMatchString(`^[\w\S]{6,18}$`, val) && gregex.IsMatchString(`[a-z]+`, val) && gregex.IsMatchString(`[A-Z]+`, val) && gregex.IsMatchString(`\d+`, val) {
match = true
}
2020-05-10 10:56:11 +08:00
// Universal password format rule3:
// Must meet password rule1, must contain lower and upper letters, numbers and special chars.
2019-06-19 09:06:52 +08:00
case "password3":
if gregex.IsMatchString(`^[\w\S]{6,18}$`, val) && gregex.IsMatchString(`[a-z]+`, val) && gregex.IsMatchString(`[A-Z]+`, val) && gregex.IsMatchString(`\d+`, val) && gregex.IsMatchString(`[^a-zA-Z0-9]+`, val) {
match = true
}
2020-05-10 10:56:11 +08:00
// Json.
2019-06-19 09:06:52 +08:00
case "json":
if _, err := gjson.Decode([]byte(val)); err == nil {
match = true
}
2020-05-10 10:56:11 +08:00
// Integer.
2019-06-19 09:06:52 +08:00
case "integer":
if _, err := strconv.Atoi(val); err == nil {
match = true
}
2020-05-10 10:56:11 +08:00
// Float.
2019-06-19 09:06:52 +08:00
case "float":
if _, err := strconv.ParseFloat(val, 10); err == nil {
match = true
}
2020-05-10 10:56:11 +08:00
// Boolean(1,true,on,yes:true | 0,false,off,no,"":false).
2019-06-19 09:06:52 +08:00
case "boolean":
match = false
if _, ok := boolMap[strings.ToLower(val)]; ok {
match = true
}
2020-05-10 10:56:11 +08:00
// Email.
2019-06-19 09:06:52 +08:00
case "email":
match = gregex.IsMatchString(`^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+)+$`, val)
// URL
case "url":
match = gregex.IsMatchString(`(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]`, val)
2020-05-10 10:56:11 +08:00
// Domain
2019-06-19 09:06:52 +08:00
case "domain":
match = gregex.IsMatchString(`^([0-9a-zA-Z][0-9a-zA-Z-]{0,62}\.)+([0-9a-zA-Z][0-9a-zA-Z-]{0,62})\.?$`, val)
2020-05-10 10:56:11 +08:00
// IP(IPv4/IPv6).
2019-06-19 09:06:52 +08:00
case "ip":
match = gipv4.Validate(val) || gipv6.Validate(val)
2020-05-10 10:56:11 +08:00
// IPv4.
2019-06-19 09:06:52 +08:00
case "ipv4":
match = gipv4.Validate(val)
2020-05-10 10:56:11 +08:00
// IPv6.
2019-06-19 09:06:52 +08:00
case "ipv6":
match = gipv6.Validate(val)
2020-05-10 10:56:11 +08:00
// MAC.
2019-06-19 09:06:52 +08:00
case "mac":
match = gregex.IsMatchString(`^([0-9A-Fa-f]{2}[\-:]){5}[0-9A-Fa-f]{2}$`, val)
default:
2020-05-10 16:48:00 +08:00
errorMsgs[ruleKey] = "Invalid rule name: " + ruleKey
2019-06-19 09:06:52 +08:00
}
2020-05-10 10:56:11 +08:00
// Error message handling.
2019-06-19 09:06:52 +08:00
if !match {
2020-05-10 10:56:11 +08:00
// It does nothing if the error message for this rule
// is already set in previous validation.
2019-06-19 09:06:52 +08:00
if _, ok := errorMsgs[ruleKey]; !ok {
if msg, ok := customMsgMap[ruleKey]; ok {
errorMsgs[ruleKey] = msg
} else {
2020-05-10 10:56:11 +08:00
errorMsgs[ruleKey] = getDefaultErrorMessageByRule(ruleKey)
2019-06-19 09:06:52 +08:00
}
}
}
index++
}
if len(errorMsgs) > 0 {
return newError([]string{rules}, ErrorMap{
2020-05-10 10:56:11 +08:00
// Single rule validation has no key.
2019-06-19 09:06:52 +08:00
"": errorMsgs,
})
}
return nil
}