validators.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package validation
  15. import (
  16. "fmt"
  17. "reflect"
  18. "regexp"
  19. "strings"
  20. "time"
  21. "unicode/utf8"
  22. )
  23. // CanSkipFuncs will skip valid if RequiredFirst is true and the struct field's value is empty
  24. var CanSkipFuncs = map[string]struct{}{
  25. "Email": {},
  26. "IP": {},
  27. "Mobile": {},
  28. "Tel": {},
  29. "Phone": {},
  30. "ZipCode": {},
  31. }
  32. // MessageTmpls store commond validate template
  33. var MessageTmpls = map[string]string{
  34. "Required": "Can not be empty",
  35. "Min": "Minimum is %d",
  36. "Max": "Maximum is %d",
  37. "Range": "Range is %d to %d",
  38. "MinSize": "Minimum size is %d",
  39. "MaxSize": "Maximum size is %d",
  40. "Length": "Required length is %d",
  41. "Alpha": "Must be valid alpha characters",
  42. "Numeric": "Must be valid numeric characters",
  43. "AlphaNumeric": "Must be valid alpha or numeric characters",
  44. "Match": "Must match %s",
  45. "NoMatch": "Must not match %s",
  46. "AlphaDash": "Must be valid alpha or numeric or dash(-_) characters",
  47. "Email": "Must be a valid email address",
  48. "IP": "Must be a valid ip address",
  49. "Base64": "Must be valid base64 characters",
  50. "Mobile": "Must be valid mobile number",
  51. "Tel": "Must be valid telephone number",
  52. "Phone": "Must be valid telephone or mobile phone number",
  53. "ZipCode": "Must be valid zipcode",
  54. }
  55. // SetDefaultMessage set default messages
  56. // if not set, the default messages are
  57. // "Required": "Can not be empty",
  58. // "Min": "Minimum is %d",
  59. // "Max": "Maximum is %d",
  60. // "Range": "Range is %d to %d",
  61. // "MinSize": "Minimum size is %d",
  62. // "MaxSize": "Maximum size is %d",
  63. // "Length": "Required length is %d",
  64. // "Alpha": "Must be valid alpha characters",
  65. // "Numeric": "Must be valid numeric characters",
  66. // "AlphaNumeric": "Must be valid alpha or numeric characters",
  67. // "Match": "Must match %s",
  68. // "NoMatch": "Must not match %s",
  69. // "AlphaDash": "Must be valid alpha or numeric or dash(-_) characters",
  70. // "Email": "Must be a valid email address",
  71. // "IP": "Must be a valid ip address",
  72. // "Base64": "Must be valid base64 characters",
  73. // "Mobile": "Must be valid mobile number",
  74. // "Tel": "Must be valid telephone number",
  75. // "Phone": "Must be valid telephone or mobile phone number",
  76. // "ZipCode": "Must be valid zipcode",
  77. func SetDefaultMessage(msg map[string]string) {
  78. if len(msg) == 0 {
  79. return
  80. }
  81. for name := range msg {
  82. MessageTmpls[name] = msg[name]
  83. }
  84. }
  85. // Validator interface
  86. type Validator interface {
  87. IsSatisfied(interface{}) bool
  88. DefaultMessage() string
  89. GetKey() string
  90. GetLimitValue() interface{}
  91. }
  92. // Required struct
  93. type Required struct {
  94. Key string
  95. }
  96. // IsSatisfied judge whether obj has value
  97. func (r Required) IsSatisfied(obj interface{}) bool {
  98. if obj == nil {
  99. return false
  100. }
  101. if str, ok := obj.(string); ok {
  102. return len(strings.TrimSpace(str)) > 0
  103. }
  104. if _, ok := obj.(bool); ok {
  105. return true
  106. }
  107. if i, ok := obj.(int); ok {
  108. return i != 0
  109. }
  110. if i, ok := obj.(uint); ok {
  111. return i != 0
  112. }
  113. if i, ok := obj.(int8); ok {
  114. return i != 0
  115. }
  116. if i, ok := obj.(uint8); ok {
  117. return i != 0
  118. }
  119. if i, ok := obj.(int16); ok {
  120. return i != 0
  121. }
  122. if i, ok := obj.(uint16); ok {
  123. return i != 0
  124. }
  125. if i, ok := obj.(uint32); ok {
  126. return i != 0
  127. }
  128. if i, ok := obj.(int32); ok {
  129. return i != 0
  130. }
  131. if i, ok := obj.(int64); ok {
  132. return i != 0
  133. }
  134. if i, ok := obj.(uint64); ok {
  135. return i != 0
  136. }
  137. if t, ok := obj.(time.Time); ok {
  138. return !t.IsZero()
  139. }
  140. v := reflect.ValueOf(obj)
  141. if v.Kind() == reflect.Slice {
  142. return v.Len() > 0
  143. }
  144. return true
  145. }
  146. // DefaultMessage return the default error message
  147. func (r Required) DefaultMessage() string {
  148. return MessageTmpls["Required"]
  149. }
  150. // GetKey return the r.Key
  151. func (r Required) GetKey() string {
  152. return r.Key
  153. }
  154. // GetLimitValue return nil now
  155. func (r Required) GetLimitValue() interface{} {
  156. return nil
  157. }
  158. // Min check struct
  159. type Min struct {
  160. Min int
  161. Key string
  162. }
  163. // IsSatisfied judge whether obj is valid
  164. // not support int64 on 32-bit platform
  165. func (m Min) IsSatisfied(obj interface{}) bool {
  166. var v int
  167. switch obj.(type) {
  168. case int64:
  169. if wordsize == 32 {
  170. return false
  171. }
  172. v = int(obj.(int64))
  173. case int:
  174. v = obj.(int)
  175. case int32:
  176. v = int(obj.(int32))
  177. case int16:
  178. v = int(obj.(int16))
  179. case int8:
  180. v = int(obj.(int8))
  181. default:
  182. return false
  183. }
  184. return v >= m.Min
  185. }
  186. // DefaultMessage return the default min error message
  187. func (m Min) DefaultMessage() string {
  188. return fmt.Sprintf(MessageTmpls["Min"], m.Min)
  189. }
  190. // GetKey return the m.Key
  191. func (m Min) GetKey() string {
  192. return m.Key
  193. }
  194. // GetLimitValue return the limit value, Min
  195. func (m Min) GetLimitValue() interface{} {
  196. return m.Min
  197. }
  198. // Max validate struct
  199. type Max struct {
  200. Max int
  201. Key string
  202. }
  203. // IsSatisfied judge whether obj is valid
  204. // not support int64 on 32-bit platform
  205. func (m Max) IsSatisfied(obj interface{}) bool {
  206. var v int
  207. switch obj.(type) {
  208. case int64:
  209. if wordsize == 32 {
  210. return false
  211. }
  212. v = int(obj.(int64))
  213. case int:
  214. v = obj.(int)
  215. case int32:
  216. v = int(obj.(int32))
  217. case int16:
  218. v = int(obj.(int16))
  219. case int8:
  220. v = int(obj.(int8))
  221. default:
  222. return false
  223. }
  224. return v <= m.Max
  225. }
  226. // DefaultMessage return the default max error message
  227. func (m Max) DefaultMessage() string {
  228. return fmt.Sprintf(MessageTmpls["Max"], m.Max)
  229. }
  230. // GetKey return the m.Key
  231. func (m Max) GetKey() string {
  232. return m.Key
  233. }
  234. // GetLimitValue return the limit value, Max
  235. func (m Max) GetLimitValue() interface{} {
  236. return m.Max
  237. }
  238. // Range Requires an integer to be within Min, Max inclusive.
  239. type Range struct {
  240. Min
  241. Max
  242. Key string
  243. }
  244. // IsSatisfied judge whether obj is valid
  245. // not support int64 on 32-bit platform
  246. func (r Range) IsSatisfied(obj interface{}) bool {
  247. return r.Min.IsSatisfied(obj) && r.Max.IsSatisfied(obj)
  248. }
  249. // DefaultMessage return the default Range error message
  250. func (r Range) DefaultMessage() string {
  251. return fmt.Sprintf(MessageTmpls["Range"], r.Min.Min, r.Max.Max)
  252. }
  253. // GetKey return the m.Key
  254. func (r Range) GetKey() string {
  255. return r.Key
  256. }
  257. // GetLimitValue return the limit value, Max
  258. func (r Range) GetLimitValue() interface{} {
  259. return []int{r.Min.Min, r.Max.Max}
  260. }
  261. // MinSize Requires an array or string to be at least a given length.
  262. type MinSize struct {
  263. Min int
  264. Key string
  265. }
  266. // IsSatisfied judge whether obj is valid
  267. func (m MinSize) IsSatisfied(obj interface{}) bool {
  268. if str, ok := obj.(string); ok {
  269. return utf8.RuneCountInString(str) >= m.Min
  270. }
  271. v := reflect.ValueOf(obj)
  272. if v.Kind() == reflect.Slice {
  273. return v.Len() >= m.Min
  274. }
  275. return false
  276. }
  277. // DefaultMessage return the default MinSize error message
  278. func (m MinSize) DefaultMessage() string {
  279. return fmt.Sprintf(MessageTmpls["MinSize"], m.Min)
  280. }
  281. // GetKey return the m.Key
  282. func (m MinSize) GetKey() string {
  283. return m.Key
  284. }
  285. // GetLimitValue return the limit value
  286. func (m MinSize) GetLimitValue() interface{} {
  287. return m.Min
  288. }
  289. // MaxSize Requires an array or string to be at most a given length.
  290. type MaxSize struct {
  291. Max int
  292. Key string
  293. }
  294. // IsSatisfied judge whether obj is valid
  295. func (m MaxSize) IsSatisfied(obj interface{}) bool {
  296. if str, ok := obj.(string); ok {
  297. return utf8.RuneCountInString(str) <= m.Max
  298. }
  299. v := reflect.ValueOf(obj)
  300. if v.Kind() == reflect.Slice {
  301. return v.Len() <= m.Max
  302. }
  303. return false
  304. }
  305. // DefaultMessage return the default MaxSize error message
  306. func (m MaxSize) DefaultMessage() string {
  307. return fmt.Sprintf(MessageTmpls["MaxSize"], m.Max)
  308. }
  309. // GetKey return the m.Key
  310. func (m MaxSize) GetKey() string {
  311. return m.Key
  312. }
  313. // GetLimitValue return the limit value
  314. func (m MaxSize) GetLimitValue() interface{} {
  315. return m.Max
  316. }
  317. // Length Requires an array or string to be exactly a given length.
  318. type Length struct {
  319. N int
  320. Key string
  321. }
  322. // IsSatisfied judge whether obj is valid
  323. func (l Length) IsSatisfied(obj interface{}) bool {
  324. if str, ok := obj.(string); ok {
  325. return utf8.RuneCountInString(str) == l.N
  326. }
  327. v := reflect.ValueOf(obj)
  328. if v.Kind() == reflect.Slice {
  329. return v.Len() == l.N
  330. }
  331. return false
  332. }
  333. // DefaultMessage return the default Length error message
  334. func (l Length) DefaultMessage() string {
  335. return fmt.Sprintf(MessageTmpls["Length"], l.N)
  336. }
  337. // GetKey return the m.Key
  338. func (l Length) GetKey() string {
  339. return l.Key
  340. }
  341. // GetLimitValue return the limit value
  342. func (l Length) GetLimitValue() interface{} {
  343. return l.N
  344. }
  345. // Alpha check the alpha
  346. type Alpha struct {
  347. Key string
  348. }
  349. // IsSatisfied judge whether obj is valid
  350. func (a Alpha) IsSatisfied(obj interface{}) bool {
  351. if str, ok := obj.(string); ok {
  352. for _, v := range str {
  353. if ('Z' < v || v < 'A') && ('z' < v || v < 'a') {
  354. return false
  355. }
  356. }
  357. return true
  358. }
  359. return false
  360. }
  361. // DefaultMessage return the default Length error message
  362. func (a Alpha) DefaultMessage() string {
  363. return MessageTmpls["Alpha"]
  364. }
  365. // GetKey return the m.Key
  366. func (a Alpha) GetKey() string {
  367. return a.Key
  368. }
  369. // GetLimitValue return the limit value
  370. func (a Alpha) GetLimitValue() interface{} {
  371. return nil
  372. }
  373. // Numeric check number
  374. type Numeric struct {
  375. Key string
  376. }
  377. // IsSatisfied judge whether obj is valid
  378. func (n Numeric) IsSatisfied(obj interface{}) bool {
  379. if str, ok := obj.(string); ok {
  380. for _, v := range str {
  381. if '9' < v || v < '0' {
  382. return false
  383. }
  384. }
  385. return true
  386. }
  387. return false
  388. }
  389. // DefaultMessage return the default Length error message
  390. func (n Numeric) DefaultMessage() string {
  391. return MessageTmpls["Numeric"]
  392. }
  393. // GetKey return the n.Key
  394. func (n Numeric) GetKey() string {
  395. return n.Key
  396. }
  397. // GetLimitValue return the limit value
  398. func (n Numeric) GetLimitValue() interface{} {
  399. return nil
  400. }
  401. // AlphaNumeric check alpha and number
  402. type AlphaNumeric struct {
  403. Key string
  404. }
  405. // IsSatisfied judge whether obj is valid
  406. func (a AlphaNumeric) IsSatisfied(obj interface{}) bool {
  407. if str, ok := obj.(string); ok {
  408. for _, v := range str {
  409. if ('Z' < v || v < 'A') && ('z' < v || v < 'a') && ('9' < v || v < '0') {
  410. return false
  411. }
  412. }
  413. return true
  414. }
  415. return false
  416. }
  417. // DefaultMessage return the default Length error message
  418. func (a AlphaNumeric) DefaultMessage() string {
  419. return MessageTmpls["AlphaNumeric"]
  420. }
  421. // GetKey return the a.Key
  422. func (a AlphaNumeric) GetKey() string {
  423. return a.Key
  424. }
  425. // GetLimitValue return the limit value
  426. func (a AlphaNumeric) GetLimitValue() interface{} {
  427. return nil
  428. }
  429. // Match Requires a string to match a given regex.
  430. type Match struct {
  431. Regexp *regexp.Regexp
  432. Key string
  433. }
  434. // IsSatisfied judge whether obj is valid
  435. func (m Match) IsSatisfied(obj interface{}) bool {
  436. return m.Regexp.MatchString(fmt.Sprintf("%v", obj))
  437. }
  438. // DefaultMessage return the default Match error message
  439. func (m Match) DefaultMessage() string {
  440. return fmt.Sprintf(MessageTmpls["Match"], m.Regexp.String())
  441. }
  442. // GetKey return the m.Key
  443. func (m Match) GetKey() string {
  444. return m.Key
  445. }
  446. // GetLimitValue return the limit value
  447. func (m Match) GetLimitValue() interface{} {
  448. return m.Regexp.String()
  449. }
  450. // NoMatch Requires a string to not match a given regex.
  451. type NoMatch struct {
  452. Match
  453. Key string
  454. }
  455. // IsSatisfied judge whether obj is valid
  456. func (n NoMatch) IsSatisfied(obj interface{}) bool {
  457. return !n.Match.IsSatisfied(obj)
  458. }
  459. // DefaultMessage return the default NoMatch error message
  460. func (n NoMatch) DefaultMessage() string {
  461. return fmt.Sprintf(MessageTmpls["NoMatch"], n.Regexp.String())
  462. }
  463. // GetKey return the n.Key
  464. func (n NoMatch) GetKey() string {
  465. return n.Key
  466. }
  467. // GetLimitValue return the limit value
  468. func (n NoMatch) GetLimitValue() interface{} {
  469. return n.Regexp.String()
  470. }
  471. var alphaDashPattern = regexp.MustCompile(`[^\d\w-_]`)
  472. // AlphaDash check not Alpha
  473. type AlphaDash struct {
  474. NoMatch
  475. Key string
  476. }
  477. // DefaultMessage return the default AlphaDash error message
  478. func (a AlphaDash) DefaultMessage() string {
  479. return MessageTmpls["AlphaDash"]
  480. }
  481. // GetKey return the n.Key
  482. func (a AlphaDash) GetKey() string {
  483. return a.Key
  484. }
  485. // GetLimitValue return the limit value
  486. func (a AlphaDash) GetLimitValue() interface{} {
  487. return nil
  488. }
  489. var emailPattern = regexp.MustCompile(`^[\w!#$%&'*+/=?^_` + "`" + `{|}~-]+(?:\.[\w!#$%&'*+/=?^_` + "`" + `{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[a-zA-Z0-9](?:[\w-]*[\w])?$`)
  490. // Email check struct
  491. type Email struct {
  492. Match
  493. Key string
  494. }
  495. // DefaultMessage return the default Email error message
  496. func (e Email) DefaultMessage() string {
  497. return MessageTmpls["Email"]
  498. }
  499. // GetKey return the n.Key
  500. func (e Email) GetKey() string {
  501. return e.Key
  502. }
  503. // GetLimitValue return the limit value
  504. func (e Email) GetLimitValue() interface{} {
  505. return nil
  506. }
  507. var ipPattern = regexp.MustCompile(`^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$`)
  508. // IP check struct
  509. type IP struct {
  510. Match
  511. Key string
  512. }
  513. // DefaultMessage return the default IP error message
  514. func (i IP) DefaultMessage() string {
  515. return MessageTmpls["IP"]
  516. }
  517. // GetKey return the i.Key
  518. func (i IP) GetKey() string {
  519. return i.Key
  520. }
  521. // GetLimitValue return the limit value
  522. func (i IP) GetLimitValue() interface{} {
  523. return nil
  524. }
  525. var base64Pattern = regexp.MustCompile(`^(?:[A-Za-z0-99+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`)
  526. // Base64 check struct
  527. type Base64 struct {
  528. Match
  529. Key string
  530. }
  531. // DefaultMessage return the default Base64 error message
  532. func (b Base64) DefaultMessage() string {
  533. return MessageTmpls["Base64"]
  534. }
  535. // GetKey return the b.Key
  536. func (b Base64) GetKey() string {
  537. return b.Key
  538. }
  539. // GetLimitValue return the limit value
  540. func (b Base64) GetLimitValue() interface{} {
  541. return nil
  542. }
  543. // just for chinese mobile phone number
  544. var mobilePattern = regexp.MustCompile(`^((\+86)|(86))?(1(([35][0-9])|[8][0-9]|[7][06789]|[4][579]))\d{8}$`)
  545. // Mobile check struct
  546. type Mobile struct {
  547. Match
  548. Key string
  549. }
  550. // DefaultMessage return the default Mobile error message
  551. func (m Mobile) DefaultMessage() string {
  552. return MessageTmpls["Mobile"]
  553. }
  554. // GetKey return the m.Key
  555. func (m Mobile) GetKey() string {
  556. return m.Key
  557. }
  558. // GetLimitValue return the limit value
  559. func (m Mobile) GetLimitValue() interface{} {
  560. return nil
  561. }
  562. // just for chinese telephone number
  563. var telPattern = regexp.MustCompile(`^(0\d{2,3}(\-)?)?\d{7,8}$`)
  564. // Tel check telephone struct
  565. type Tel struct {
  566. Match
  567. Key string
  568. }
  569. // DefaultMessage return the default Tel error message
  570. func (t Tel) DefaultMessage() string {
  571. return MessageTmpls["Tel"]
  572. }
  573. // GetKey return the t.Key
  574. func (t Tel) GetKey() string {
  575. return t.Key
  576. }
  577. // GetLimitValue return the limit value
  578. func (t Tel) GetLimitValue() interface{} {
  579. return nil
  580. }
  581. // Phone just for chinese telephone or mobile phone number
  582. type Phone struct {
  583. Mobile
  584. Tel
  585. Key string
  586. }
  587. // IsSatisfied judge whether obj is valid
  588. func (p Phone) IsSatisfied(obj interface{}) bool {
  589. return p.Mobile.IsSatisfied(obj) || p.Tel.IsSatisfied(obj)
  590. }
  591. // DefaultMessage return the default Phone error message
  592. func (p Phone) DefaultMessage() string {
  593. return MessageTmpls["Phone"]
  594. }
  595. // GetKey return the p.Key
  596. func (p Phone) GetKey() string {
  597. return p.Key
  598. }
  599. // GetLimitValue return the limit value
  600. func (p Phone) GetLimitValue() interface{} {
  601. return nil
  602. }
  603. // just for chinese zipcode
  604. var zipCodePattern = regexp.MustCompile(`^[1-9]\d{5}$`)
  605. // ZipCode check the zip struct
  606. type ZipCode struct {
  607. Match
  608. Key string
  609. }
  610. // DefaultMessage return the default Zip error message
  611. func (z ZipCode) DefaultMessage() string {
  612. return MessageTmpls["ZipCode"]
  613. }
  614. // GetKey return the z.Key
  615. func (z ZipCode) GetKey() string {
  616. return z.Key
  617. }
  618. // GetLimitValue return the limit value
  619. func (z ZipCode) GetLimitValue() interface{} {
  620. return nil
  621. }