validators.go 15 KB

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