Form validation

The Form validation module is used for data validation and error collection.

Installing and testing

Installing:

  1. go get github.com/beego/beego/v2/core/validation

Testing:

  1. go test github.com/beego/beego/v2/core/validation

Localization

In order to localize validation error messages, one might use SetDefaultMessage function of the validation package.

Note that format markers (%d, %s) must be preserved in translated text to provide resulting messages with validation context values.

Default template messages are present in validation.MessageTmpls variable.

Simple message localization for Russian language:

  1. import "github.com/beego/beego/v2/core/validation"
  2. func init() {
  3. validation.SetDefaultMessage(map[string]string{
  4. "Required": "Должно быть заполнено",
  5. "Min": "Минимально допустимое значение %d",
  6. "Max": "Максимально допустимое значение %d",
  7. "Range": "Должно быть в диапазоне от %d до %d",
  8. "MinSize": "Минимально допустимая длина %d",
  9. "MaxSize": "Максимально допустимая длина %d",
  10. "Length": "Длина должна быть равна %d",
  11. "Alpha": "Должно состоять из букв",
  12. "Numeric": "Должно состоять из цифр",
  13. "AlphaNumeric": "Должно состоять из букв или цифр",
  14. "Match": "Должно совпадать с %s",
  15. "NoMatch": "Не должно совпадать с %s",
  16. "AlphaDash": "Должно состоять из букв, цифр или символов (-_)",
  17. "Email": "Должно быть в правильном формате email",
  18. "IP": "Должен быть правильный IP адрес",
  19. "Base64": "Должно быть представлено в правильном формате base64",
  20. "Mobile": "Должно быть правильным номером мобильного телефона",
  21. "Tel": "Должно быть правильным номером телефона",
  22. "Phone": "Должно быть правильным номером телефона или мобильного телефона",
  23. "ZipCode": "Должно быть правильным почтовым индексом",
  24. })
  25. }

Examples:

Direct use:

  1. import (
  2. "github.com/beego/beego/v2/core/validation"
  3. "log"
  4. )
  5. type User struct {
  6. Name string
  7. Age int
  8. }
  9. func main() {
  10. u := User{"man", 40}
  11. valid := validation.Validation{}
  12. valid.Required(u.Name, "name")
  13. valid.MaxSize(u.Name, 15, "nameMax")
  14. valid.Range(u.Age, 0, 18, "age")
  15. if valid.HasErrors() {
  16. // If there are error messages it means the validation didn't pass
  17. // Print error message
  18. for _, err := range valid.Errors {
  19. log.Println(err.Key, err.Message)
  20. }
  21. }
  22. // or use like this
  23. if v := valid.Max(u.Age, 140, "age"); !v.Ok {
  24. log.Println(v.Error.Key, v.Error.Message)
  25. }
  26. // Customize error messages
  27. minAge := 18
  28. valid.Min(u.Age, minAge, "age").Message("18+ only!!")
  29. // Format error messages
  30. valid.Min(u.Age, minAge, "age").Message("%d+", minAge)
  31. }

Use through StructTag

  1. import (
  2. "log"
  3. "strings"
  4. "github.com/beego/beego/v2/core/validation"
  5. )
  6. // Set validation function in "valid" tag
  7. // Use ";" as the separator of multiple functions. Spaces accept after ";"
  8. // Wrap parameters with "()" and separate parameter with ",". Spaces accept after ","
  9. // Wrap regex match with "//"
  10. //
  11. // 各个函数的结果的key值为字段名.验证函数名
  12. type user struct {
  13. Id int
  14. Name string `valid:"Required;Match(/^Bee.*/)"` // Name can't be empty or start with Bee
  15. Age int `valid:"Range(1, 140)"` // 1 <= Age <= 140, only valid in this range
  16. Email string `valid:"Email; MaxSize(100)"` // Need to be a valid Email address and no more than 100 characters.
  17. Mobile string `valid:"Mobile"` // Must be a valid mobile number
  18. IP string `valid:"IP"` // Must be a valid IPv4 address
  19. }
  20. // If your struct implemented interface `validation.ValidFormer`
  21. // When all tests in StructTag succeed, it will execute Valid function for custom validation
  22. func (u *user) Valid(v *validation.Validation) {
  23. if strings.Index(u.Name, "admin") != -1 {
  24. // Set error messages of Name by SetError and HasErrors will return true
  25. v.SetError("Name", "Can't contain 'admin' in Name")
  26. }
  27. }
  28. func main() {
  29. valid := validation.Validation{}
  30. u := user{Name: "Beego", Age: 2, Email: "dev@beego.vip"}
  31. b, err := valid.Valid(&u)
  32. if err != nil {
  33. // handle error
  34. }
  35. if !b {
  36. // validation does not pass
  37. // blabla...
  38. for _, err := range valid.Errors {
  39. log.Println(err.Key, err.Message)
  40. }
  41. }
  42. }

Available validation functions in StrucTag:

  • Required not empty. :TODO 不为空,即各个类型要求不为其零值
  • Min(min int) minimum value. Valid type is int, all other types are invalid.
  • Max(max int) maximum value. Valid type is int, all other types are invalid.
  • Range(min, max int) Value range. Valid type is int, all other types are invalid.
  • MinSize(min int) minimum length. Valid type is string slice, all other types are invalid.
  • MaxSize(max int) maximum length. Valid type is string slice, all other types are invalid.
  • Length(length int) fixed length. Valid type is string slice, all other types are invalid.
  • Alpha alpha characters. Valid type is string, all other types are invalid.
  • Numeric numerics. Valid type is string, all other types are invalid.
  • AlphaNumeric alpha characters or numerics. Valid type is string, all other types are invalid.
  • Match(pattern string) regex matching. Valid type is string, all other types will be cast to string then match. (fmt.Sprintf(“%v”, obj).Match)
  • AlphaDash alpha characters or numerics or -_. Valid type is string, all other types are invalid.
  • Email Email address. Valid type is string, all other types are invalid.
  • IP IP address,Only support IPv4 address. Valid type is string, all other types are invalid.
  • Base64 base64 encoding. Valid type is string, all other types are invalid.
  • Mobile mobile number. Valid type is string, all other types are invalid.
  • Tel telephone number. Valid type is string, all other types are invalid.
  • Phone mobile number or telephone number. Valid type is string, all other types are invalid.
  • ZipCode zip code. Valid type is string, all other types are invalid.

API doc

Please see Go Walker