validate

package
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2026 License: MIT Imports: 11 Imported by: 0

README

Validation Library

A flexible, tag-based struct validator and assertion library.

Features

  • Tag-based Validation: Validate struct fields using valid:"tag" syntax.
  • Rich Validator Set: Includes checks for required, email, numeric, len, uuid, etc.
  • Custom Response: Returns structured error messages useful for API responses.
  • Standalone Assertions: Use validator functions directly without structs.

Installation

go get github.com/mbu-id/engine/validate

Usage

Struct Validation
type UserRequest struct {
    Name     string `json:"name" valid:"required|alpha_space"`
    Email    string `json:"email" valid:"required|email"`
    Age      int    `json:"age" valid:"numeric|gte:18"`
    Password string `json:"password" valid:"required|password"`
}

func ValidateUser(req UserRequest) {
    v := validate.New()

    // Validate struct
    response := v.Struct(req)

    if !response.Valid {
        // Get generic error strings
        fmt.Println(response.GetFailures())
        // Output: map[email:email is not valid age:age must be greater than or equal 18]
    }
}
Standalone Assertions

You can use the validate (or alias assert depending on import) functions directly.

import "github.com/mbu-id/engine/validate"

if !validate.IsEmail("test@example.com") {
    // handle error
}

if validate.IsNumeric("12345") {
    // it is numeric
}
Available Tags
Tag Description Example
required Field cannot be zero-value valid:"required"
email Must be a valid email valid:"email"
numeric Must contain only numbers valid:"numeric"
alpha Must contain only letters valid:"alpha"
uuid Must be a valid UUID valid:"uuid"
min:x Min length/value valid:"min:10"
max:x Max length/value valid:"max:20"
gte:x Greater than or equal valid:"gte:18"
lte:x Less than or equal valid:"lte:100"
oneof Must be one of values valid:"oneof:A,B,C"
password Complex password check valid:"password"
Customizing Messages

Implement the Request interface to provide custom error messages.

func (r UserRequest) Messages() map[string]string {
    return map[string]string{
        "required": "The %s field is mandatory.",
        "email":    "Please provide a valid email address.",
    }
}

func (r UserRequest) Validate() *validate.Response {
    // Custom logic if needed
    return nil
}

// Then use v.Request(req) instead of v.Struct(req)
res := v.Request(req)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsAlpha

func IsAlpha(value interface{}) bool

IsAlpha check if the value contains only letters (a-zA-Z). Empty string is valid.

func IsAlphaSpace

func IsAlphaSpace(value interface{}) bool

IsAlphaSpace check if the value contains only letters and space. Empty string is valid.

func IsAlphanumeric

func IsAlphanumeric(value interface{}) bool

IsAlphanumeric check if the value contains only letters and numbers. Empty string is valid.

func IsAlphanumericSpace

func IsAlphanumericSpace(value interface{}) bool

IsAlphanumericSpace check if the value contains only letters, numbers and space. Empty string is valid.

func IsContains

func IsContains(value interface{}, substring string) bool

IsContains check if the value contains the substring.

func IsEmail

func IsEmail(value interface{}) bool

IsEmail check if the value is an email.

func IsGreaterThan

func IsGreaterThan(value interface{}, min interface{}) (res bool)

IsGreaterThan return true if value is greather than given number this will evaluate value of int, lenght of string and number of slices.

func IsGreaterThanEqual

func IsGreaterThanEqual(value interface{}, min interface{}) (res bool)

IsGreaterThanEqual return true if value is greather than equal given number this will evaluate value of int, lenght of string and number of slices.

func IsIn

func IsIn(value interface{}, param ...string) bool

IsIn check if the value is exists in given param

func IsJSON

func IsJSON(value interface{}) bool

IsJSON check if the value is valid JSON (note: uses json.Unmarshal).

func IsLatitude

func IsLatitude(value interface{}) bool

IsLatitude check if the value is an latitude.

func IsLongitude

func IsLongitude(value interface{}) bool

IsLongitude check if the value is an longitude.

func IsLowerThan

func IsLowerThan(value interface{}, max interface{}) (res bool)

IsLowerThan return true if value is lower than given number this will evaluate value of int, lenght of string and number of slices.

func IsLowerThanEqual

func IsLowerThanEqual(value interface{}, max interface{}) (res bool)

IsLowerThanEqual return true if value is greather than equal given number this will evaluate value of int, lenght of string and number of slices.

func IsMatches

func IsMatches(value interface{}, pattern string) bool

IsMatches check if value matches the pattern (pattern is regular expression) In case of error return false

func IsNotEmpty

func IsNotEmpty(value interface{}) bool

IsNotEmpty returns true if value is not nill

func IsNotIn

func IsNotIn(value interface{}, param ...string) bool

IsNotIn check if the value is not exists in given param

func IsNumeric

func IsNumeric(value interface{}) bool

IsNumeric check if the value contains only numbers.

func IsOnRange

func IsOnRange(value interface{}, min interface{}, max interface{}) bool

IsOnRange return true if value is greather than equal given min and lowerthan than equal given max this will evaluate value of int, lenght of string and number of slices.

func IsPassword

func IsPassword(value interface{}) bool

IsPassword validates password according to policy: - Minimum 8 characters - At least one uppercase letter - At least one lowercase letter - At least one number - At least one special character - Not in common passwords list

func IsSame

func IsSame(value interface{}, param interface{}) bool

IsSame check if the value is identicaly same with given param

func IsURL

func IsURL(value interface{}) bool

IsURL check if the value is an URL.

func ValidDate

func ValidDate(text string, f string) (result time.Time, e error)

func ValidPhone

func ValidPhone(text string) (p string, e error)

Types

type Request

type Request interface {
	Validate() *Response
	Messages() map[string]string
}

Request interface validation requests

type Response

type Response struct {
	Valid         bool   // state of validation
	HeaderMessage string // header message in json
	// contains filtered or unexported fields
}

Response format when running validations

func NewResponse

func NewResponse() *Response

NewResponse create new instance responses

func (*Response) Error

func (res *Response) Error() string

func (*Response) GetError

func (res *Response) GetError(k string) string

GetError returns failure message by key provided as parameter,

func (*Response) GetFailures

func (res *Response) GetFailures() map[string]string

GetFailures return all failure message from validations.

func (*Response) GetMessages

func (res *Response) GetMessages() map[string]string

GetMessages return all error messages.

func (*Response) SetError

func (res *Response) SetError(k string, e string)

SetError set an failure message as key and value

type Validator

type Validator struct {
	TagName      string
	ValidatorFns map[string]validatorFn
}

Validator holding the tag name and taglists available

func New

func New() *Validator

New creates a new Validation instances.

func (*Validator) Field

func (v *Validator) Field(value interface{}, tag string) (res *Response)

Field validates a value based on the provided tags and returns validator response

func (*Validator) Request

func (v *Validator) Request(object Request) (res *Response)

Request same as Validation.Struct but, this should be implement an ValidationRequest interfaces so we can do some custom validation and custome error messages.

func (*Validator) Struct

func (v *Validator) Struct(object interface{}) (res *Response)

Struct validates the object of a struct based on 'valid' tags and returns errors found indexed by the field name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL