Validation

Sometimes (often) you want to validate user inputs. After looking at some validation library we decided to use ozzo-validation. Your structure needs to implement :

  • ValidateWithContext(ctx context.Context) error

  • or Validate() error

Example

package main

import (
   "net/http"

   validation "github.com/alexisvisco/ozzo-validation/v4"
   "github.com/alexisvisco/ozzo-validation/v4/is"
   "github.com/go-chi/chi"

   "github.com/alexisvisco/kcd"
)

func main() {
   r := chi.NewRouter()
   r.Get("/{name}", kcd.Handler(YourHttpHandler, http.StatusOK))
   _ = http.ListenAndServe(":3000", r)
}

// CreateCustomerInput is an example of input for an http request.
type CreateCustomerInput struct {
   Name   string   `path:"name"`
}

func (c *CreateCustomerInput) Validate() error {
   return validation.ValidateStruct(c,
      validation.Field(&c.Name, validation.Required, is.Alpha))
}

// YourHttpHandler is here using the ctx of the request.
func YourHttpHandler(c *CreateCustomerInput) (*CreateCustomerInput, error) {
   return c, nil
}

// Test it : curl localhost:3000/alexis

If you test this code with a curl localhost:3000/123 you will get an error because the name must be alphabetical as described in the Validate function.

You will get something like this:

{
  "error_description": "the request has one or multiple invalid fields",
  "error": "invalid_argument",
  "fields": {
    "name": "must contain English letters only"
  }
}

Go to the error page to get more information.

Last updated