gvalid_check.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // Copyright 2017-2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gvalid
  7. import (
  8. "errors"
  9. "github.com/gogf/gf/internal/json"
  10. "github.com/gogf/gf/net/gipv4"
  11. "github.com/gogf/gf/net/gipv6"
  12. "github.com/gogf/gf/os/gtime"
  13. "github.com/gogf/gf/text/gregex"
  14. "github.com/gogf/gf/util/gconv"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. )
  19. const (
  20. // regular expression pattern for single validation rule.
  21. singleRulePattern = `^([\w-]+):{0,1}(.*)`
  22. invalidRulesErrKey = "invalid_rules"
  23. invalidParamsErrKey = "invalid_params"
  24. invalidObjectErrKey = "invalid_object"
  25. )
  26. var (
  27. // all internal error keys.
  28. internalErrKeyMap = map[string]string{
  29. invalidRulesErrKey: invalidRulesErrKey,
  30. invalidParamsErrKey: invalidParamsErrKey,
  31. invalidObjectErrKey: invalidObjectErrKey,
  32. }
  33. // regular expression object for single rule
  34. // which is compiled just once and of repeatable usage.
  35. ruleRegex, _ = regexp.Compile(singleRulePattern)
  36. // mustCheckRulesEvenValueEmpty specifies some rules that must be validated
  37. // even the value is empty (nil or empty).
  38. mustCheckRulesEvenValueEmpty = map[string]struct{}{
  39. "required": {},
  40. "required-if": {},
  41. "required-unless": {},
  42. "required-with": {},
  43. "required-with-all": {},
  44. "required-without": {},
  45. "required-without-all": {},
  46. //"same": {},
  47. //"different": {},
  48. //"in": {},
  49. //"not-in": {},
  50. //"regex": {},
  51. }
  52. // allSupportedRules defines all supported rules that is used for quick checks.
  53. allSupportedRules = map[string]struct{}{
  54. "required": {},
  55. "required-if": {},
  56. "required-unless": {},
  57. "required-with": {},
  58. "required-with-all": {},
  59. "required-without": {},
  60. "required-without-all": {},
  61. "date": {},
  62. "date-format": {},
  63. "email": {},
  64. "phone": {},
  65. "phone-loose": {},
  66. "telephone": {},
  67. "passport": {},
  68. "password": {},
  69. "password2": {},
  70. "password3": {},
  71. "postcode": {},
  72. "resident-id": {},
  73. "bank-card": {},
  74. "qq": {},
  75. "ip": {},
  76. "ipv4": {},
  77. "ipv6": {},
  78. "mac": {},
  79. "url": {},
  80. "domain": {},
  81. "length": {},
  82. "min-length": {},
  83. "max-length": {},
  84. "between": {},
  85. "min": {},
  86. "max": {},
  87. "json": {},
  88. "integer": {},
  89. "float": {},
  90. "boolean": {},
  91. "same": {},
  92. "different": {},
  93. "in": {},
  94. "not-in": {},
  95. "regex": {},
  96. }
  97. // boolMap defines the boolean values.
  98. boolMap = map[string]struct{}{
  99. "1": {},
  100. "true": {},
  101. "on": {},
  102. "yes": {},
  103. "": {},
  104. "0": {},
  105. "false": {},
  106. "off": {},
  107. "no": {},
  108. }
  109. )
  110. // Check checks single value with specified rules.
  111. // It returns nil if successful validation.
  112. //
  113. // The parameter <value> can be any type of variable, which will be converted to string
  114. // for validation.
  115. // The parameter <rules> can be one or more rules, multiple rules joined using char '|'.
  116. // The parameter <messages> specifies the custom error messages, which can be type of:
  117. // string/map/struct/*struct.
  118. // The optional parameter <params> specifies the extra validation parameters for some rules
  119. // like: required-*、same、different, etc.
  120. func Check(value interface{}, rules string, messages interface{}, params ...interface{}) *Error {
  121. return doCheck("", value, rules, messages, params...)
  122. }
  123. // doCheck does the really rules validation for single key-value.
  124. func doCheck(key string, value interface{}, rules string, messages interface{}, params ...interface{}) *Error {
  125. // If there's no validation rules, it does nothing and returns quickly.
  126. if rules == "" {
  127. return nil
  128. }
  129. // It converts value to string and then does the validation.
  130. var (
  131. // Do not trim it as the space is also part of the value.
  132. data = make(map[string]string)
  133. errorMsgArray = make(map[string]string)
  134. )
  135. if len(params) > 0 {
  136. for k, v := range gconv.Map(params[0]) {
  137. data[k] = gconv.String(v)
  138. }
  139. }
  140. // Custom error messages handling.
  141. var (
  142. msgArray = make([]string, 0)
  143. customMsgMap = make(map[string]string)
  144. )
  145. switch v := messages.(type) {
  146. case string:
  147. msgArray = strings.Split(v, "|")
  148. default:
  149. for k, v := range gconv.Map(messages) {
  150. customMsgMap[k] = gconv.String(v)
  151. }
  152. }
  153. // Handle the char '|' in the rule,
  154. // which makes this rule separated into multiple rules.
  155. ruleItems := strings.Split(strings.TrimSpace(rules), "|")
  156. for i := 0; ; {
  157. array := strings.Split(ruleItems[i], ":")
  158. _, ok := allSupportedRules[array[0]]
  159. if !ok && customRuleFuncMap[array[0]] == nil {
  160. if i > 0 && ruleItems[i-1][:5] == "regex" {
  161. ruleItems[i-1] += "|" + ruleItems[i]
  162. ruleItems = append(ruleItems[:i], ruleItems[i+1:]...)
  163. } else {
  164. return newErrorStr(
  165. invalidRulesErrKey,
  166. invalidRulesErrKey+": "+rules,
  167. )
  168. }
  169. } else {
  170. i++
  171. }
  172. if i == len(ruleItems) {
  173. break
  174. }
  175. }
  176. for index := 0; index < len(ruleItems); {
  177. var (
  178. err error
  179. match = false
  180. results = ruleRegex.FindStringSubmatch(ruleItems[index])
  181. ruleKey = strings.TrimSpace(results[1])
  182. rulePattern = strings.TrimSpace(results[2])
  183. )
  184. if len(msgArray) > index {
  185. customMsgMap[ruleKey] = strings.TrimSpace(msgArray[index])
  186. }
  187. if f, ok := customRuleFuncMap[ruleKey]; ok {
  188. // It checks custom validation rules with most priority.
  189. var (
  190. dataMap map[string]interface{}
  191. message = getErrorMessageByRule(ruleKey, customMsgMap)
  192. )
  193. if len(params) > 0 {
  194. dataMap = gconv.Map(params[0])
  195. }
  196. if err := f(ruleItems[index], value, message, dataMap); err != nil {
  197. match = false
  198. errorMsgArray[ruleKey] = err.Error()
  199. } else {
  200. match = true
  201. }
  202. } else {
  203. // It checks build-in validation rules if there's no custom rule.
  204. match, err = doCheckBuildInRules(index, value, ruleKey, rulePattern, ruleItems, data, customMsgMap)
  205. if !match && err != nil {
  206. errorMsgArray[ruleKey] = err.Error()
  207. }
  208. }
  209. // Error message handling.
  210. if !match {
  211. // It does nothing if the error message for this rule
  212. // is already set in previous validation.
  213. if _, ok := errorMsgArray[ruleKey]; !ok {
  214. errorMsgArray[ruleKey] = getErrorMessageByRule(ruleKey, customMsgMap)
  215. }
  216. }
  217. index++
  218. }
  219. if len(errorMsgArray) > 0 {
  220. return newError([]string{rules}, ErrorMap{
  221. key: errorMsgArray,
  222. })
  223. }
  224. return nil
  225. }
  226. func doCheckBuildInRules(
  227. index int,
  228. value interface{},
  229. ruleKey string,
  230. rulePattern string,
  231. ruleItems []string,
  232. dataMap map[string]string,
  233. customMsgMap map[string]string,
  234. ) (match bool, err error) {
  235. valueStr := gconv.String(value)
  236. switch ruleKey {
  237. // Required rules.
  238. case
  239. "required",
  240. "required-if",
  241. "required-unless",
  242. "required-with",
  243. "required-with-all",
  244. "required-without",
  245. "required-without-all":
  246. match = checkRequired(valueStr, ruleKey, rulePattern, dataMap)
  247. // Length rules.
  248. // It also supports length of unicode string.
  249. case
  250. "length",
  251. "min-length",
  252. "max-length":
  253. if msg := checkLength(valueStr, ruleKey, rulePattern, customMsgMap); msg != "" {
  254. return match, errors.New(msg)
  255. } else {
  256. match = true
  257. }
  258. // Range rules.
  259. case
  260. "min",
  261. "max",
  262. "between":
  263. if msg := checkRange(valueStr, ruleKey, rulePattern, customMsgMap); msg != "" {
  264. return match, errors.New(msg)
  265. } else {
  266. match = true
  267. }
  268. // Custom regular expression.
  269. case "regex":
  270. // It here should check the rule as there might be special char '|' in it.
  271. for i := index + 1; i < len(ruleItems); i++ {
  272. if !gregex.IsMatchString(singleRulePattern, ruleItems[i]) {
  273. rulePattern += "|" + ruleItems[i]
  274. index++
  275. }
  276. }
  277. match = gregex.IsMatchString(rulePattern, valueStr)
  278. // Date rules.
  279. case "date":
  280. // Standard date string, which must contain char '-' or '.'.
  281. if _, err := gtime.StrToTime(valueStr); err == nil {
  282. match = true
  283. break
  284. }
  285. // Date that not contains char '-' or '.'.
  286. if _, err := gtime.StrToTime(valueStr, "Ymd"); err == nil {
  287. match = true
  288. break
  289. }
  290. // Date rule with specified format.
  291. case "date-format":
  292. if _, err := gtime.StrToTimeFormat(valueStr, rulePattern); err == nil {
  293. match = true
  294. } else {
  295. var msg string
  296. msg = getErrorMessageByRule(ruleKey, customMsgMap)
  297. msg = strings.Replace(msg, ":format", rulePattern, -1)
  298. return match, errors.New(msg)
  299. }
  300. // Values of two fields should be equal as string.
  301. case "same":
  302. if v, ok := dataMap[rulePattern]; ok {
  303. if strings.Compare(valueStr, v) == 0 {
  304. match = true
  305. }
  306. }
  307. if !match {
  308. var msg string
  309. msg = getErrorMessageByRule(ruleKey, customMsgMap)
  310. msg = strings.Replace(msg, ":field", rulePattern, -1)
  311. return match, errors.New(msg)
  312. }
  313. // Values of two fields should not be equal as string.
  314. case "different":
  315. match = true
  316. if v, ok := dataMap[rulePattern]; ok {
  317. if strings.Compare(valueStr, v) == 0 {
  318. match = false
  319. }
  320. }
  321. if !match {
  322. var msg string
  323. msg = getErrorMessageByRule(ruleKey, customMsgMap)
  324. msg = strings.Replace(msg, ":field", rulePattern, -1)
  325. return match, errors.New(msg)
  326. }
  327. // Field value should be in range of.
  328. case "in":
  329. array := strings.Split(rulePattern, ",")
  330. for _, v := range array {
  331. if strings.Compare(valueStr, strings.TrimSpace(v)) == 0 {
  332. match = true
  333. break
  334. }
  335. }
  336. // Field value should not be in range of.
  337. case "not-in":
  338. match = true
  339. array := strings.Split(rulePattern, ",")
  340. for _, v := range array {
  341. if strings.Compare(valueStr, strings.TrimSpace(v)) == 0 {
  342. match = false
  343. break
  344. }
  345. }
  346. // Phone format validation.
  347. // 1. China Mobile:
  348. // 134, 135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159, 182, 183, 184, 187, 188,
  349. // 178(4G), 147(Net);
  350. // 172
  351. //
  352. // 2. China Unicom:
  353. // 130, 131, 132, 155, 156, 185, 186 ,176(4G), 145(Net), 175
  354. //
  355. // 3. China Telecom:
  356. // 133, 153, 180, 181, 189, 177(4G)
  357. //
  358. // 4. Satelite:
  359. // 1349
  360. //
  361. // 5. Virtual:
  362. // 170, 173
  363. //
  364. // 6. 2018:
  365. // 16x, 19x
  366. case "phone":
  367. match = gregex.IsMatchString(`^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^16[\d]{9}$|^17[0,2,3,5,6,7,8]{1}\d{8}$|^18[\d]{9}$|^19[\d]{9}$`, valueStr)
  368. // Loose mobile phone number verification(宽松的手机号验证)
  369. // As long as the 11 digit numbers beginning with
  370. // 13, 14, 15, 16, 17, 18, 19 can pass the verification (只要满足 13、14、15、16、17、18、19开头的11位数字都可以通过验证)
  371. case "phone-loose":
  372. match = gregex.IsMatchString(`^1(3|4|5|6|7|8|9)\d{9}$`, valueStr)
  373. // Telephone number:
  374. // "XXXX-XXXXXXX"
  375. // "XXXX-XXXXXXXX"
  376. // "XXX-XXXXXXX"
  377. // "XXX-XXXXXXXX"
  378. // "XXXXXXX"
  379. // "XXXXXXXX"
  380. case "telephone":
  381. match = gregex.IsMatchString(`^((\d{3,4})|\d{3,4}-)?\d{7,8}$`, valueStr)
  382. // QQ number: from 10000.
  383. case "qq":
  384. match = gregex.IsMatchString(`^[1-9][0-9]{4,}$`, valueStr)
  385. // Postcode number.
  386. case "postcode":
  387. match = gregex.IsMatchString(`^\d{6}$`, valueStr)
  388. // China resident id number.
  389. //
  390. // xxxxxx yyyy MM dd 375 0 十八位
  391. // xxxxxx yy MM dd 75 0 十五位
  392. //
  393. // 地区: [1-9]\d{5}
  394. // 年的前两位:(18|19|([23]\d)) 1800-2399
  395. // 年的后两位:\d{2}
  396. // 月份: ((0[1-9])|(10|11|12))
  397. // 天数: (([0-2][1-9])|10|20|30|31) 闰年不能禁止29+
  398. //
  399. // 三位顺序码:\d{3}
  400. // 两位顺序码:\d{2}
  401. // 校验码: [0-9Xx]
  402. //
  403. // 十八位:^[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]$
  404. // 十五位:^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$
  405. //
  406. // 总:
  407. // (^[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}$)
  408. case "resident-id":
  409. match = checkResidentId(valueStr)
  410. // Bank card number using LUHN algorithm.
  411. case "bank-card":
  412. match = checkLuHn(valueStr)
  413. // Universal passport format rule:
  414. // Starting with letter, containing only numbers or underscores, length between 6 and 18.
  415. case "passport":
  416. match = gregex.IsMatchString(`^[a-zA-Z]{1}\w{5,17}$`, valueStr)
  417. // Universal password format rule1:
  418. // Containing any visible chars, length between 6 and 18.
  419. case "password":
  420. match = gregex.IsMatchString(`^[\w\S]{6,18}$`, valueStr)
  421. // Universal password format rule2:
  422. // Must meet password rule1, must contain lower and upper letters and numbers.
  423. case "password2":
  424. if gregex.IsMatchString(`^[\w\S]{6,18}$`, valueStr) &&
  425. gregex.IsMatchString(`[a-z]+`, valueStr) &&
  426. gregex.IsMatchString(`[A-Z]+`, valueStr) &&
  427. gregex.IsMatchString(`\d+`, valueStr) {
  428. match = true
  429. }
  430. // Universal password format rule3:
  431. // Must meet password rule1, must contain lower and upper letters, numbers and special chars.
  432. case "password3":
  433. if gregex.IsMatchString(`^[\w\S]{6,18}$`, valueStr) &&
  434. gregex.IsMatchString(`[a-z]+`, valueStr) &&
  435. gregex.IsMatchString(`[A-Z]+`, valueStr) &&
  436. gregex.IsMatchString(`\d+`, valueStr) &&
  437. gregex.IsMatchString(`[^a-zA-Z0-9]+`, valueStr) {
  438. match = true
  439. }
  440. // Json.
  441. case "json":
  442. if json.Valid([]byte(valueStr)) {
  443. match = true
  444. }
  445. // Integer.
  446. case "integer":
  447. if _, err := strconv.Atoi(valueStr); err == nil {
  448. match = true
  449. }
  450. // Float.
  451. case "float":
  452. if _, err := strconv.ParseFloat(valueStr, 10); err == nil {
  453. match = true
  454. }
  455. // Boolean(1,true,on,yes:true | 0,false,off,no,"":false).
  456. case "boolean":
  457. match = false
  458. if _, ok := boolMap[strings.ToLower(valueStr)]; ok {
  459. match = true
  460. }
  461. // Email.
  462. case "email":
  463. match = gregex.IsMatchString(`^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+)+$`, valueStr)
  464. // URL
  465. case "url":
  466. match = gregex.IsMatchString(`(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]`, valueStr)
  467. // Domain
  468. case "domain":
  469. match = gregex.IsMatchString(`^([0-9a-zA-Z][0-9a-zA-Z\-]{0,62}\.)+([a-zA-Z]{0,62})$`, valueStr)
  470. // IP(IPv4/IPv6).
  471. case "ip":
  472. match = gipv4.Validate(valueStr) || gipv6.Validate(valueStr)
  473. // IPv4.
  474. case "ipv4":
  475. match = gipv4.Validate(valueStr)
  476. // IPv6.
  477. case "ipv6":
  478. match = gipv6.Validate(valueStr)
  479. // MAC.
  480. case "mac":
  481. match = gregex.IsMatchString(`^([0-9A-Fa-f]{2}[\-:]){5}[0-9A-Fa-f]{2}$`, valueStr)
  482. default:
  483. return match, errors.New("Invalid rule name: " + ruleKey)
  484. }
  485. return match, nil
  486. }