Validation

Gozen provides several different approaches to validate your application's incoming data. It is most common to use the validate method available on all incoming HTTP requests. However, we will discuss other approaches to validation as well.



Example

Let's assume we want to validate a login form with POST data. We'll walk you through Gozen's simple yet powerful validation helper.



The controller

package login

import (
	"github.com/go-chi/chi/v5"
	"gozen/system/validation"
	"net/http"
)

func Login(w http.ResponseWriter, r *http.Request) {

	v := &validation.Validator{}

    v.Rules("email", r.FormValue("email"), "required|email|unique:users:email|max:255")
    v.Rules("password", r.FormValue("password"), "required")
	
	postData := templates.PostData(w, r)

	if v.HasErrors() {
		templates.Errors(w, r, v, postData, "login")
		return
	}
    //else success

	http.Redirect(w, r, "/dashboard", http.StatusFound)
}

and the

login.html

{{ template "_header.html" }}
<div>
   {{ if .Data.FlashData }}
      <div>
         <div class="text-danger">Error</div>
         <div class="text-danger">
            {{ .Data.FlashData }}
         </div>
      </div>
   {{ end }}
   <h4>Login</h4>
   <form method="POST" action="/login">
      {{ .Csrf }}
      <div>
         <label for="email">Email</label>
         <div >Enter a valid email address</div>
         <input
            class=""
            type="text"
            name="email"
            value="{{ .Data.PostData.email }}"
            placeholder="" />
         <div class="text-danger">{{ .Data.PostDataErrors.email }}</div>
      </div>
      <div>
         <label for="password">Password</label>
         <div>Password</div>
         <input
            class=""
            type="password"
            name="password"
            placeholder="" />
      </div>
      <div>
         <button type="submit">
            Submit
         </button>
      </div>
   </form>
   <div>
      <a href="/forgot">Forgot password</a>
   </div>
</div>
{{ template "_footer.html" }}

In this example we have succinctly validated the email, checked if it doesn't conflict with the users table stored in the database, and we've returned flash data to the view to repopulate the form

Available validation rules

  • unique (database)
  • exists (database)
  • required
  • min
  • max
  • email
  • alpha
  • alphanum
  • integer
  • float
  • date
  • date_less_than
  • date_greater_than