validations

Validations is a GORM extension, used to validate models when creating, updating

  • 所有者: qor/validations
  • 平台:
  • 许可证: MIT License
  • 分类:
  • 主题:
  • 喜欢:
    0
      比较:

Github星跟踪图

Validations

Validations provides a means to validate GORM models when creating and updating them.

Register GORM Callbacks

Validations uses GORM callbacks to handle validations, so you will need to register callbacks first:

import (
  "github.com/jinzhu/gorm"
  "github.com/qor/validations"
)

func main() {
  db, err := gorm.Open("sqlite3", "demo_db")

  validations.RegisterCallbacks(db)
}

Usage

After callbacks have been registered, attempting to create or update any record will trigger the Validate method that you have implemented for your model. If your implementation adds or returns an error, the attempt will be aborted.

type User struct {
  gorm.Model
  Age uint
}

func (user User) Validate(db *gorm.DB) {
  if user.Age <= 18 {
    db.AddError(errors.New("age need to be 18+"))
  }
}

db.Create(&User{Age: 10})         // won't insert the record into database, as the `Validate` method will return error

var user User{Age: 20}
db.Create(&user)                  // user with age 20 will be inserted into database
db.Model(&user).Update("age", 10) // user's age won't be updated, will return error `age need to be 18+`

// If you have added more than one error, could get all of them with `db.GetErrors()`
func (user User) Validate(db *gorm.DB) {
  if user.Age <= 18 {
    db.AddError(errors.New("age need to be 18+"))
  }
  if user.Name == "" {
    db.AddError(errors.New("name can't be blank"))
  }
}

db.Create(&User{}).GetErrors() // => []error{"age need to be 18+", "name can't be blank"}

Govalidator integration

Qor Validations supports govalidator, so you could add a tag into your struct for some common validations, such as check required, numeric, length, etc.

type User struct {
  gorm.Model
  Name           string `valid:"required"`
  Password       string `valid:"length(6, 20)"`
  SecurePassword string `valid:"numeric"`
  Email          string `valid:"email"`
}

Customize errors on form field

If you want to display errors for each form field in QOR Admin, you could register your error like this:

func (user User) Validate(db *gorm.DB) {
  if user.Age <= 18 {
    db.AddError(validations.NewError(user, "Age", "age need to be 18+"))
  }
}

Try it out for yourself

Checkout the http://demo.getqor.com/admin/products/1 demo, change Name to be a blank string and save to see what happens.

License

Released under the MIT License.

主要指标

概览
名称与所有者qor/validations
主编程语言Go
编程语言Go (语言数: 1)
平台
许可证MIT License
所有者活动
创建于2016-01-12 03:20:48
推送于2024-06-17 06:20:06
最后一次提交2017-12-28 20:26:39
发布数2
最新版本名称v1.1 (发布于 )
第一版名称v1.0 (发布于 2016-04-27 20:10:59)
用户参与
星数135
关注者数15
派生数43
提交数25
已启用问题?
问题数5
打开的问题数4
拉请求数2
打开的拉请求数4
关闭的拉请求数5
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?