gogo-gin

Validation in GO "ozzo-validation"


I'm a beginner in GO :) just try to create simple crud throw it using gin and plugin called ozzo-validation

My code:

package models

import (
    validation "github.com/go-ozzo/ozzo-validation"
    "gorm.io/gorm"
)

type Post struct {
    gorm.Model
    Name string `gorm:"type:varchar(255);"`
    Desc string `gorm:"type:varchar(500);"`
}

type PostData struct {
    Name string `json:"name"`
    Desc string `json:"desc"`
}

func (p PostData) Validate() error {
    return validation.ValidateStruct(&p,
        validation.Field(&p.Name, validation.Required, validation.Length(5, 20)),
        validation.Field(&p.Desc, validation.Required),
    )
}

PostController:

package controllers

import (
    "curd/app/models"
    "fmt"
    "github.com/gin-gonic/gin"
)

func Store(c *gin.Context) {
    // Validate Input
    var post models.PostData
    err := post.Validate()
    fmt.Println(err)
}
{
  "name": "sdfsdfsfsdf"
}

The problem is once I submit the above JSON data from the postman the validation gives me this in terminal :

desc: cannot be blank; name: cannot be blank.

Solution

  • As noted in the comments, you need to decode the data from the HTTP request into the struct before you can perform validation. The validation errors you're seeing are a product of calling Validate() on a fresh instance (with zero values in every field) of your Post struct. Try this.

    func Store(c *gin.Context) {
        var post models.PostData
        // This will infer what binder to use depending on the content-type header.
        if err := c.ShouldBind(&post); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        // Validate Input
        err := post.Validate()
        fmt.Println(err)
    }