Skip to content

Validation ​

All validator function

Base on

  1. asaskevich/govalidator: [Go] Package of validators and sanitizers for strings, numerics, slices and structs (github.com)
  2. thedevsaddam/gojsonq: A simple Go package to Query over JSON/YAML/XML/CSV Data (github.com)

Example ​

go
package requests

import (
  "gitlab.finema.co/finema/golang-template/models"
  core "gitlab.finema.co/finema/idin-core"
)

type UserCreate struct {
  core.BaseValidator 
  Email    *string `json:"email"`      // Email field for user creation
  FullName *string `json:"full_name"`  // Full name field for user creation
}


func (r *UserCreate) Valid(ctx core.IContext) core.IError {
  // Check if the email is valid format
  r.Must(r.IsEmail(r.Email, "email"))
  
  // Check if the email is not empty
  r.Must(r.IsStrRequired(r.Email, "email"))
  
  // Check if the email is unique in the database
  r.Must(r.IsStrUnique(ctx, r.Email, models.User{}.TableName(), "email", "", "email"))

  // Check if the full name is not empty
  r.Must(r.IsStrRequired(r.FullName, "full_name")) 

  return r.Error()
}
go
package user

import (
	"gitlab.finema.co/finema/golang-template/requests"
	"gitlab.finema.co/finema/golang-template/services"
	core "gitlab.finema.co/finema/idin-core"
	"gitlab.finema.co/finema/idin-core/utils"
	"net/http"
)

type UserController struct {
}

func (m UserController) Create(c core.IHTTPContext) error {
	// Create an instance of UserCreate struct to hold the request data
	input := &requests.UserCreate{}

	// Bind the request body to the input struct and validate the input
	if err := c.BindWithValidate(input); err != nil {
		return c.JSON(err.GetStatus(), err.JSON())
	}

	// Create an instance of UserService
	userSvc := services.NewUserService(c)

	// Create a payload to pass to the userSvc.Create method
	payload := &services.UserCreatePayload{}
	_ = utils.Copy(payload, input)

	// Call the userSvc.Create method to create a new user
	user, err := userSvc.Create(payload)
	if err != nil {
		return c.JSON(err.GetStatus(), err.JSON())
	}

	// Return the created user as JSON response
	return c.JSON(http.StatusCreated, user)
}

Example response (Return HTTP Status 400) ​

json

{
    "code": "INVALID_PARAMS",
    "message": "Invalid parameters",
    "fields": {
        "password": {
            "code": "REQUIRED",
            "message": "The password field is required"
        },
        "username": {
            "code": "REQUIRED",
            "message": "The username field is required"
        }
    }
}

Rules that touch the database ​

IsStrUnique, IsExists, IsMongoStrUnique and the rest of the Database rules run a query to reach their verdict. When that query fails, there is no verdict to give: nothing is yet known about whether the value is taken or whether the row exists.

So a database that cannot be reached fails the whole validation with 500 DATABASE_ERROR, rather than reporting a field-level result it has no grounds for:

json
{
  "code": "DATABASE_ERROR",
  "message": "database internal error"
}

This outranks any field violations collected alongside it, and it travels up through Merge and AddValidator from nested validators. A 400 saying "this email is available" while the database is down is worse than no answer — it is a wrong answer that a client will act on.

Changed in v1.5

Earlier versions dropped the query error. IsStrUnique reported every value as unique for as long as the database was unreachable — the check that exists to protect a unique column let everything through it — and IsExists answered 400 "does not exist" for what is a 500. No code change is needed on your side; the rules simply report correctly now.

All validators ​


Here's the list of functions organized by function category in a table format:

String ​


Function NameFunction NameFunction Name
IsStrInIsStrMaxIsStrMin
IsStrRequiredIsStrUniqueIsStringContain
IsStringEndWithIsStringLowercaseIsStringNotContain
IsStringNumberIsStringNumberMinIsStringStartWith
IsStringUppercase

Array ​

Function NameFunction NameFunction Name
IsArrayBetweenIsArrayBetweenIsArrayMax
IsArrayMaxIsArrayMinIsArrayMin
IsArraySizeIsArraySize

Number ​


Function NameFunction NameFunction Name
IsFloatNumberBetweenIsFloatNumberMaxIsFloatNumberMin
IsNumberBetweenIsNumberMaxIsNumberMin

Date and Time ​


Function NameFunction NameFunction Name
IsDateTimeIsDateTimeAfterIsDateTimeBefore
IsTimeIsTimeAfterIsTimeBefore
IsTimeRequired

JSON ​


Function NameFunction NameFunction Name
IsJSONArrayIsJSONArrayMaxIsJSONArrayMin
IsJSONBoolPathRequiredIsJSONObjectIsJSONObjectNotEmpty
IsJSONObjectPathIsJSONPathRequireNotEmptyIsJSONPathRequired
IsJSONPathStrInIsJSONRequiredIsJSONStrPathRequired
LoopJSONArray

Email ​


Function Name
IsEmail

Database ​


Function NameFunction Name
IsExistsIsExistsWithCondition
IsMongoExistsWithConditionIsMongoStrUnique
IsMongoExistsWithConditionIsStrUnique

Base64 ​

Function Name
IsBase64

Boolean ​


Function NameFunction Name
IsBoolRequired

Custom ​

Function NameFunction Name
IsCustom

IP Address ​


Function Name
IsIP

Required ​


Function NameFunction Name
IsRequiredIsRequiredArray

URL ​


Function Name
IsURL

Maintained by Passakon Puttasuwan & Dev Core Team.