translation based validator.
Each validation method generate ErrorResponse
.
Note: ErrorResponse implements json Marshaller and toString interface by default.
ErrorResponse interface contains following methods:
Add new error to errors list.
// Signature:
AddError(field, tag, message string)
// Example:
errs.AddError("username", "pattern", "Username can contains alphnum characters only!")
Check if response has error.
// Signature:
HasError() bool
// Example:
if errs.HasError() {
// Return 422 status
}else{
// Save record and return 200 status
}
Check if field has error.
// Signature:
Failed(field string) bool
// Example:
if errs.Failed("username"){
// Username field has some error
}
Check if field has special error.
// Signature:
FailedOn(field, err string) bool
// Example:
if errs.FailedOn("username", "pattern"){
// Username field has pattern error
}
Get errors list as map.
// Signature:
Errors() map[string]map[string]string
Convert error response to string.
// Signature:
String() string
Get error messages only without error key
// Signature:
Messages() map[string][]string
Get error rules only without error message.
// Signature:
Rules() map[string][]string
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!" } }
}
Generate invalid state for field.
// Signature:
Invalidate(field, err string) ErrorResponse
You can access custom validations by function.
import "github.com/gomig/validator"
if validator.IsIDNumber(1234) {
// This is a valid id number
}
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":{...}
// }
Validator use three special tags for translating error message.
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"`
}
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"`
}
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
Validator based on github.com/go-playground/validator/v10
and github.com/gomig/translator
packages.
Note: Validator library contains translation for go builtin validator functions.
// Signature:
NewValidator(t translator.Translator, locale string) Validator
// Example:
import "github.com/gomig/validator"
import "github.com/gomig/validator/translations"
v := NewValidator(t, "en")
translations.RegisterENValidationMessages(v) // EN
translations.RegisterFAValidationMessages(v)// FA (Persian)
Validator interface contains following methods:
Note: You must pass app locale for generating localization message.
Get original validator instance
// Signature:
Validator() *validator.Validate
Register new validator function.
// Signature:
AddValidation(tag string, v validator.Func)
Register new translation message to validator translator.
// Signature:
AddTranslation(locale string, key string, message string)
Generate translation. used internally by validator!
// Signature:
Translate(locale string, key string, placeholders map[string]string) string
Generate translation for struct. used internally by validator!
// Signature:
TranslateStruct(s any, locale string, key string, field string, placeholders map[string]string) string
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
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
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
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" })
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
Validator contains some extra validation commands you can register and use with your validator.
you can find this validations under github.com/gomig/validator/validations
namespace.
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=' -_'"`
}
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=' '"`
}
Check if field is a credit card number.
type Person struct{
Field string `validate:"creditcard"`
}
Check if field is a valid numeric greater than 1.
type Person struct{
Field string `validate:"identifier"`
}
Check if field is a valid id number (number has 1-10 length).
type Person struct{
Field string `validate:"idnumber"`
}
Check if field is a valid ip:port string.
type Person struct{
Field string `validate:"ipport"`
}
Check if field is a valid persian date string.
type Person struct{
Field string `validate:"jalaali"`
}
Check if field is a valid persian mobile number.
type Person struct{
Field string `validate:"mobile"`
}
Check if field is a valid persian national code.
type Person struct{
Field string `validate:"nationalcode"`
}
Check if field is a valid persian postal code.
type Person struct{
Field string `validate:"postalcode"`
}
Check if field is a valid persian tel.
type Person struct{
Field string `validate:"tel"`
}
Check if field is a valid unsigned number (0 or greater).
type Person struct{
Field string `validate:"unsigned"`
}
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"`
}
Check if field is a valid uuid.
type Person struct{
Field string `validate:"uuid"`
}