Validating Domain Objects in Revel

Moving further from showing a login/signup page, Now we need get user to fill up the sign up details, and validate them before saving in database.

Consider User struct, as defined

package models
 
import (
    "github.com/coopernurse/gorp"
    "github.com/revel/revel"   
)
 
type User struct {
    Id               int64
    Email            string
    FirstName        string
    LastName         string
    Password         string
}

Further, consider that none of the above fields can be null or empty and FirstName and LastName are not more then 30 characters each.

These constraints can be specified at the database level when we provide mapping between domain model and database.

However, we need to validate these constraints, before hitting database, to improve performance and minimize database calls.

In comes the validations support provided by revel.

After user submits a form, the form values come to an action “Signup”, part of which looks like

func (c Register) Signup(user *models.User) revel.Result {
	user.Validate(c.Validation)
	if c.Validation.HasErrors() {
		c.Validation.Keep()
		c.FlashParams()
		return c.Redirect(Register.Index)
	}

Here, we call Validate() method on user to validate the user details. The Validate() method looks like

func (user User) Validate(v *revel.Validation) {
	v.Required(user.Email).Message("Email is required")
	v.Email(user.Email).Message("Email you entered is not a valid email")
	v.MaxSize(user.FirstName, 30).Message("First Name can not be more than 30 characters long")
	v.Required(user.FirstName).Message("First Name is required")
	v.Required(user.LastName).Message("Last Name is required")
	v.MaxSize(user.LastName, 30).Message("Last Name can not be more than 30 characters long")
	v.Required(user.Password).Message("Password is required")

Here, we define constraints on fields of user struct and provide error messages for each validation.

Going back to Signup action, we check for any validation errors, without hitting database, and put them in the flash scope and redirect to page where those messages can be shown to the user.

Isn’t this awesome!

~~ Whizdumb ~~
Email : sachin.xpert@gmail.com