govalidator

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2021 License: MIT Imports: 3 Imported by: 0

README

govalidator

Go Validator

document

Access api and example document

Documentation

Overview

Example
package main

import (
	"errors"
	"fmt"

	"github.com/swordlib/govalidator"
)

type person struct {
	FirstName string
}

func main() {
	gv := govalidator.New(govalidator.RulesMap{
		"FirstName": {
			{
				Required: true,
			},
			{
				Validator: func(rule *govalidator.Rule, value interface{}, target interface{}) error {

					if v := value.(string); v != "Alice" {
						return errors.New("FirstName must be Alice")
					}
					return nil
				},
			},
		},
	})
	fmt.Println(gv.StructFirst(&person{
		FirstName: "",
	}))
	fmt.Println(gv.StructFirst(&person{
		FirstName: "Bob",
	}))
	fmt.Println(gv.StructFirst(&person{
		FirstName: "Alice",
	}))

	custom := govalidator.New(govalidator.RulesMap{
		"FirstName": {
			{
				Required: true,
				Message:  "Please input your firstName",
			},
		},
	})
	fmt.Println(custom.StructFirst(&person{}))
}
Output:

FirstName is required
FirstName must be Alice
<nil>
Please input your firstName

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Rule

type Rule struct {
	Required  bool
	Validator ValidatorFunc
	Message   string
}

type Rules

type Rules []*Rule

type RulesMap

type RulesMap map[string]Rules

type Validator

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

Validator is a validation program for go

func New

func New(rules RulesMap, varoptions ...*ValidatorOptions) *Validator

New create a new validator

func (*Validator) StructFirst added in v0.0.2

func (v *Validator) StructFirst(target interface{}) error

StructFirst Validate a struct and stop when it encounter the first error. It will panic when call with other than struct or validate a not present struct field

type ValidatorFunc added in v0.1.0

type ValidatorFunc func(rule *Rule, value interface{}, target interface{}) error

ValidatorFunc is a custom validator type, alias of func(rule *Rule, value interface{}, target interface{}) error

type ValidatorOptions

type ValidatorOptions struct {
}

ValidatorOptions It's not used until now, just reserves for future

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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