github.com/rotblauer/buffalo@v0.7.1-0.20170112214545-7aa55ef80dd3/examples/json-resource/models/user.go (about) 1 package models 2 3 import ( 4 "encoding/json" 5 "time" 6 7 "github.com/markbates/going/validate" 8 "github.com/markbates/going/validate/validators" 9 "github.com/markbates/pop" 10 ) 11 12 type User struct { 13 ID int `json:"id" db:"id"` 14 CreatedAt time.Time `json:"created_at" db:"created_at"` 15 UpdatedAt time.Time `json:"updated_at" db:"updated_at"` 16 FirstName string `json:"first_name" db:"first_name"` 17 LastName string `json:"last_name" db:"last_name"` 18 Email string `json:"email" db:"email"` 19 } 20 21 // String is not required by pop and may be deleted 22 func (u User) String() string { 23 b, _ := json.Marshal(u) 24 return string(b) 25 } 26 27 func (u *User) ValidateNew(tx *pop.Connection) (*validate.Errors, error) { 28 verrs, err := u.validateCommon(tx) 29 verrs.Append(validate.Validate( 30 &validators.FuncValidator{ 31 Fn: func() bool { 32 var b bool 33 if u.Email != "" { 34 b, err = tx.Where("email = ?", u.Email).Exists(u) 35 } 36 return !b 37 }, 38 Field: "Email", 39 Message: "%s was already taken.", 40 }, 41 )) 42 return verrs, err 43 } 44 45 func (u *User) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { 46 verrs, err := u.validateCommon(tx) 47 verrs.Append(validate.Validate( 48 &validators.FuncValidator{ 49 Fn: func() bool { 50 var b bool 51 if u.Email != "" { 52 b, err = tx.Where("email = ? and id != ?", u.Email, u.ID).Exists(u) 53 } 54 return !b 55 }, 56 Field: "Email", 57 Message: "%s was already taken.", 58 }, 59 )) 60 return verrs, err 61 } 62 63 func (u *User) validateCommon(tx *pop.Connection) (*validate.Errors, error) { 64 verrs := validate.Validate( 65 &validators.StringIsPresent{Name: "First Name", Field: u.FirstName}, 66 &validators.StringIsPresent{Name: "Last Name", Field: u.LastName}, 67 &validators.StringIsPresent{Name: "Email", Field: u.Email}, 68 ) 69 return verrs, nil 70 } 71 72 // Users is not required by pop and may be deleted 73 type Users []User 74 75 // String is not required by pop and may be deleted 76 func (u Users) String() string { 77 b, _ := json.Marshal(u) 78 return string(b) 79 }