validator

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2021 License: Apache-2.0 Imports: 6 Imported by: 8

README

Validator

Enhanced the https://github.com/go-playground/validator library, support:

  • Declare the customizable tag of regular expressions
Usage

First, declare a struct and add validate tag.

type Struct struct {
    Field `validate:"min=1,max=6"`
}

Or declare a regular expression in some complex scenes.

const commonNameRegexString = `^[a-zA-Z0-9][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$`

type Struct struct {
    Field `validate:"min=1,max=6,commonName"`
}

func init() {
    validator.RegisterRegexRules([]*validator.RegexValidateRule{
		validator.NewRegexRule("commonName", commonNameRegexString),
	})
}

Finally, add validator check to specific business code.

it := &Struct {
    Field: "AB**CD"
}
if err := validator.Validate(it); err != nil {
    // handle err
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var GlobalValidator = NewValidator()

Functions

func RegisterRegexRules

func RegisterRegexRules(rules []*RegexValidateRule) error

func Validate

func Validate(v interface{}) error

Validate validates data

func Wrap3rdTagsTranslation

func Wrap3rdTagsTranslation() error

Types

type RegexValidateRule

type RegexValidateRule struct {
	// contains filtered or unexported fields
}

RegexValidateRule contains an validate tag's info

func NewRegexRule

func NewRegexRule(tag, regexStr string) *RegexValidateRule

NewRegexRule news a rule

func (*RegexValidateRule) Explain

func (r *RegexValidateRule) Explain() string

Explain explains the rule

func (*RegexValidateRule) Tag

func (r *RegexValidateRule) Tag() string

Tag returns the validate rule's tag

func (*RegexValidateRule) Validate

func (r *RegexValidateRule) Validate(s string) bool

Validate validates string

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator validates data not safe, use it after initialized

func NewValidator

func NewValidator() *Validator

NewValidator news a validator

func (*Validator) AddErrorTranslation4Tag

func (v *Validator) AddErrorTranslation4Tag(tag string) error

AddErrorTranslation4Tag adds translation for the errors of some tag, to make the error easier to understand

func (*Validator) RegisterRule

func (v *Validator) RegisterRule(r *RegexValidateRule) error

RegisterRule registers a custom validate rule

func (*Validator) Validate

func (v *Validator) Validate(i interface{}) error

Validate validates the input data

Jump to

Keyboard shortcuts

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