validator

package module
v1.1.8 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2022 License: MIT Imports: 13 Imported by: 0

README

Validator

translation based validator.

Requirements

Error Response

Each validation method generate ErrorResponse.

Note: ErrorResponse implements json Marshaller and toString interface by default.

Usage

ErrorResponse interface contains following methods:

AddError

Add new error to errors list.

// Signature:
AddError(field, tag, message string)

// Example:
errs.AddError("username", "pattern", "Username can contains alphnum characters only!")
HasError

Check if response has error.

// Signature:
HasError() bool

// Example:
if errs.HasError() {
    // Return 422 status
}else{
    // Save record and return 200 status
}
Failed

Check if field has error.

// Signature:
Failed(field string) bool

// Example:
if errs.Failed("username"){
    // Username field has some error
}
FailedOn

Check if field has special error.

// Signature:
FailedOn(field, err string) bool

// Example:
if errs.FailedOn("username", "pattern"){
    // Username field has pattern error
}
Errors

Get errors list as map.

// Signature:
Errors() map[string]map[string]string
String

Convert error response to string.

// Signature:
String() string
Messages

Get error messages only without error key

// Signature:
Messages() map[string][]string
Rules

Get error rules only without error message.

// Signature:
Rules() map[string][]string
MarshalJSON

Convert error response to json.

// Signature:
MarshalJSON() ([]byte, error)

// Example:
if resp, err := errs.MarshalJSON(); err == nil{
    fmt.Println(string(resp)) // { "username": { "required":"username is required", "pattern":"username pattern is wrong!" } }
}
Helpers
Invalidate

Generate invalid state for field.

// Signature:
Invalidate(field, err string) ErrorResponse
Validation functions

You can access custom validations by function.

import "github.com/bopher/validator"
if validator.IsIDNumber(1234) {
    // This is a valid id number
}
Field Name

Validator get field friendly name from struct tag or ValidatorParam.

For struct tags, validator get field name from field, json, form and xml tag in order. if field name not specified by tag validator use Field Struct name as field name.

For ValidatorParam, validator get field name from ValidatorParam.Name field.

type Person struct{
    Name string `validate:"required" json:"firstname"`
    Family string `validate:"required"`
}

// => error response
// {
//     "firstname":{...},
//     "Family":{...}
// }
Helper Tags

Validator use three special tags for translating error message.

vTitle

This tag use as field title in error messages. you can combine this tag with locale key for use translation. if this parameter not passed validator use field name as title.

type Person struct{
    Name string `validate:"required" vTitle_fa:"نام" vTitle:"Firstname"`
}
vParam

When use validator that contains another field (like eqcsfield), you can use this tag for parameter title like vTitle tag. if this parameter not passed validator use validation param itself.

type Person struct{
    Password string `validate:"required" form:"pswd" vTitle_fa:"رمز"`
    PasswordRe string `validate:"eqcsfield:password" form:"pswd_re" vTitle_fa:"تایید رمز" vTitle:"Password repeat" vParam_fa:"رمز" vParam:"password"`
}
vFormat

When use this tag validator parameter formatted as number.

type Transaction struct{
    Amount string `validate:"gt=1000" xml:"amount" vTitle_fa:"مبلغ" vFormat`
}

//  => Error Message: amount must be greater than 1,000

Create New Validator

Validator based on github.com/go-playground/validator/v10 and github.com/bopher/translator packages.

Note: Validator library contains translation for go builtin validator functions.

// Signature:
NewValidator(t translator.Translator, locale string) Validator

// Example:
import "github.com/bopher/validator"
import "github.com/bopher/validator/translations"
v := NewValidator(t, "en")
translations.RegisterENValidationMessages(v) // EN
translations.RegisterFAValidationMessages(v)// FA (Persian)

Usage

Validator interface contains following methods:

Note: You must pass app locale for generating localization message.

Validator

Get original validator instance

// Signature:
Validator() *validator.Validate
AddValidation

Register new validator function.

// Signature:
AddValidation(tag string, v validator.Func)
AddTranslation

Register new translation message to validator translator.

// Signature:
AddTranslation(locale string, key string, message string)
Translate

Generate translation. used internally by validator!

// Signature:
Translate(locale string, key string, placeholders map[string]string) string
TranslateStruct

Generate translation for struct. used internally by validator!

// Signature:
TranslateStruct(s any, locale string, key string, field string, placeholders map[string]string) string
Struct

Validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified.

NOTE: You can use StructLocale method for generate error message in non-default validator locale.

// Signature:
Struct(s any) ErrorResponse
StructExcept

Validates all fields except the ones passed in.

NOTE: You can use StructExceptLocale method for generate error message in non-default validator locale.

// Signature:
StructExcept(s any, fields ...string) ErrorResponse
StructPartial

Validates the fields passed in only, ignoring all others.

NOTE: You can use StructPartialLocale method for generate error message in non-default validator locale.

// Signature:
StructPartial(s any, fields ...string) ErrorResponse
Var

Validates a single variable using tag style validation. You must use ValidatorParam for customizing var validation.

NOTE: You can use VarLocale method for generate error message in non-default validator locale.

Caution: Name field is required and if not passed in params this validation generate a panic!

ValidatorParam fields:

  • Name: this field name. e.g firstname
  • Title: validation field title. works like vTitle tag
  • ParamTitle: validation param title. works like vParam tag
  • Format: format validation param if set to true. works like vFormat tag
// Signature:
Var(params ValidatorParam, field any, tag string, messages map[string]string) ErrorResponse

Note: You can pass a message list to override default translation messages.

v.Var(params, field, "validate:required", map[string]string{ "required":"enter your name" })
VarWithValue

Validates a single variable, against another variable/field's value using tag style validation.

NOTE: You can use VarWithValueLocale method for generate error message in non-default validator locale.

// Signature:
VarWithValue(params ValidatorParam, field any, other any, tag string, messages map[string]string) ErrorResponse

Extra Validation Commands

Validator contains some extra validation commands you can register and use with your validator.

you can find this validations under github.com/bopher/validator/validations namespace.

AlphaNum

Check if field is a string contains alpha and number. You can allow extra character by listing them in param.

type Person struct{
    Field string `validate:"alnum=' -_'"`
}
AlphaNumFa

Check if field is a string contains alpha (en and fa) and number (en only). You can allow extra character by listing them in param.

type Person struct{
    Field string `validate:"alnumfa=' '"`
}
Credit Card

Check if field is a credit card number.

type Person struct{
    Field string `validate:"creditcard"`
}
Identifier

Check if field is a valid numeric greater than 1.

type Person struct{
    Field string `validate:"identifier"`
}
ID Number

Check if field is a valid id number (number has 1-10 length).

type Person struct{
    Field string `validate:"idnumber"`
}
IP Port

Check if field is a valid ip:port string.

type Person struct{
    Field string `validate:"ipport"`
}
Jalali

Check if field is a valid persian date string.

type Person struct{
    Field string `validate:"jalali"`
}
Mobile

Check if field is a valid persian mobile number.

type Person struct{
    Field string `validate:"mobile"`
}
National Code

Check if field is a valid persian national code.

type Person struct{
    Field string `validate:"nationalcode"`
}
Postal Code

Check if field is a valid persian postal code.

type Person struct{
    Field string `validate:"postalcode"`
}
Tel

Check if field is a valid persian tel.

type Person struct{
    Field string `validate:"tel"`
}
Unsigned

Check if field is a valid unsigned number (0 or greater).

type Person struct{
    Field string `validate:"unsigned"`
}
Username

Check if field is a valid username (can contains 0-9, a-a, A-Z dash, dot and underscore).

type Person struct{
    Field string `validate:"username"`
}
UUID

Check if field is a valid uuid.

type Person struct{
    Field string `validate:"uuid"`
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ISNationalCode

func ISNationalCode(idNum string) bool

ISNationalCode check if string is valid id national code

func IsCreditCardNumber

func IsCreditCardNumber(num string) bool

IsCreditCardNumber check if string is valid id credit card number

func IsIDNumber

func IsIDNumber(idNum string) bool

IsIDNumber check if string is valid id number

func IsIP

func IsIP(address string) bool

IsIP check if address if a valid ip

func IsIPPort

func IsIPPort(address string) bool

IsIPPort check if address if a valid ip contains port

func IsIdentifier

func IsIdentifier(id string) bool

IsIdentifier check if string is valid identifier

func IsMobile

func IsMobile(mobile string) bool

IsMobile check if string is valid mobile number (IR numbers)

func IsPostalcode

func IsPostalcode(postalCode string) bool

IsPostalcode check if string is valid postal code

func IsTel

func IsTel(tel string) bool

IsTel check if string is valid tel (IR numbers)

func IsUUID

func IsUUID(uuid string) bool

IsUUID check if string is valid uuid

func IsUnsigned

func IsUnsigned(num string) bool

IsUnsigned check if string is unsigned number

func IsUsername

func IsUsername(username string) bool

IsUsername check if string is valid username

func ValidateUploadExt

func ValidateUploadExt(file *multipart.FileHeader, exts ...string) (bool, error)

ValidateUploadExt check if file upload extension is valid

func ValidateUploadMime

func ValidateUploadMime(file *multipart.FileHeader, mimes ...string) (bool, error)

ValidateUploadMime check if file upload mime is valid

func ValidateUploadSize

func ValidateUploadSize(file *multipart.FileHeader, min string, max string) (bool, error)

ValidateUploadSize check if file size in range use B, KB, MB, GB for size string ex: 1KB, 3MB Note: not use float point!

Types

type ErrorResponse

type ErrorResponse interface {
	// AddError add new error
	AddError(field, tag, message string)
	// HasError check if response has error
	HasError() bool
	// Failed check if field has error
	// @example:
	// resp.Failed("firstname")
	Failed(field string) bool
	// FailedOn check if field has special error
	// @example:
	// resp.FailedOn("firstname", "required")
	FailedOn(field, err string) bool
	// Errors get errors list
	Errors() map[string]map[string]string
	// String convert to string
	String() string
	// Messages get error messages only without error key
	Messages() map[string][]string
	// Rules get error rules only without error message
	Rules() map[string][]string
	// MarshalJSON convert to json
	MarshalJSON() ([]byte, error)
}

ErrorResponse interface

func Invalidate added in v1.1.0

func Invalidate(field, err string) ErrorResponse

Invalidate generate invalid state for field

func NewErrorResponse

func NewErrorResponse() ErrorResponse

NewErrorResponse create new error response instance

type Validator

type Validator interface {
	// Validator get original validator instance
	Validator() *validator.Validate
	// AddValidation add new validator
	AddValidation(tag string, v validator.Func)

	// AddTranslation register new translation message to validator translator
	AddTranslation(locale string, key string, message string)
	// Translate generate translation
	Translate(locale string, key string, placeholders map[string]string) string
	// TranslateStruct generate translation for struct
	TranslateStruct(s any, locale string, key string, field string, placeholders map[string]string) string

	// Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified.
	// Return translated errors list on fails
	// Return nil on no error
	// use vTitle tag for define field title, (use vTitle_locale) for localization
	// use vParam tag for define param title in multifield validations (like eqcsfield). this tag follow vTitle tag rules
	// use vFormat tag for format parameter as number
	StructLocale(locale string, s any) ErrorResponse
	// Validate using default locale
	// @see StructLocale
	Struct(s any) ErrorResponse
	// StructExcept validates all fields except the ones passed in.
	// Return translated errors list on fails
	// Return nil on no error
	StructExceptLocale(locale string, s any, fields ...string) ErrorResponse
	// Validate using default locale
	// @see StructExceptLocale
	StructExcept(s any, fields ...string) ErrorResponse
	// StructPartial validates the fields passed in only, ignoring all others.
	// Return translated errors list on fails
	// Return nil on no error
	StructPartialLocale(locale string, s any, fields ...string) ErrorResponse
	// Validate using default locale
	// @see StructPartialLocale
	StructPartial(s any, fields ...string) ErrorResponse

	// Var validates a single variable using tag style validation.
	// Return translated errors list on fails
	// Return nil on no error
	VarLocale(locale string, params ValidatorParam, field any, tag string, messages map[string]string) ErrorResponse
	// Validate using default locale
	// @see VarLocale
	Var(params ValidatorParam, field any, tag string, messages map[string]string) ErrorResponse
	// VarWithValue validates a single variable, against another variable/field's value using tag style validation
	// Return translated errors list on fails
	// Return nil on no error
	VarWithValueLocale(locale string, params ValidatorParam, field any, other any, tag string, messages map[string]string) ErrorResponse
	// Validate using default locale
	// @see VarWithValueLocale
	VarWithValue(params ValidatorParam, field any, other any, tag string, messages map[string]string) ErrorResponse
}

Validator interface

func NewValidator

func NewValidator(t translator.Translator, locale string) Validator

NewValidator create new validator

type ValidatorParam

type ValidatorParam struct {
	Name       string
	Title      string
	ParamTitle string
	Format     bool
}

ValidatorParam for generate error message

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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