Convert Figma logo to code with AI

gookit logovalidate

⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器,支持自定义验证器、自定义消息、字段翻译。

1,053
116
1,053
24

Top Related Projects

16,709

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.

An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.

Quick Overview

gookit/validate is a Go package that provides powerful data validation functionality for structs, maps, and more. It offers a flexible and extensible validation system with built-in rules and the ability to create custom validators, making it suitable for various validation scenarios in Go applications.

Pros

  • Supports validation for structs, maps, and individual values
  • Offers a wide range of built-in validation rules
  • Allows for easy creation of custom validation rules
  • Provides localization support for error messages

Cons

  • Learning curve for complex validation scenarios
  • Documentation could be more comprehensive
  • Some advanced features may require additional setup

Code Examples

Validating a struct:

type User struct {
    Name  string `validate:"required|minLen:5"`
    Email string `validate:"required|email"`
    Age   int    `validate:"required|int|min:18|max:99"`
}

user := &User{
    Name:  "John",
    Email: "invalid-email",
    Age:   16,
}

v := validate.Struct(user)
if !v.Validate() {
    fmt.Println(v.Errors)
}

Validating a map:

data := map[string]interface{}{
    "name":  "John",
    "email": "john@example.com",
    "age":   25,
}

v := validate.Map(data)
v.StringRule("name", "required|minLen:4")
v.StringRule("email", "required|email")
v.IntRule("age", "required|int|min:18|max:99")

if v.Validate() {
    fmt.Println("Validation passed")
} else {
    fmt.Println(v.Errors)
}

Creating a custom validator:

validate.AddValidator("custom_rule", func(val interface{}, args ...interface{}) bool {
    str, ok := val.(string)
    if !ok {
        return false
    }
    return strings.HasPrefix(str, "prefix_")
})

v := validate.New("my_field", "some_value")
v.AddRule("custom_rule")

if v.Validate() {
    fmt.Println("Validation passed")
} else {
    fmt.Println(v.Errors)
}

Getting Started

To use gookit/validate in your Go project:

  1. Install the package:

    go get github.com/gookit/validate
    
  2. Import the package in your code:

    import "github.com/gookit/validate"
    
  3. Create a validator and define rules:

    v := validate.New("field_name", "field_value")
    v.StringRule("required|minLen:5|maxLen:20")
    
  4. Perform validation:

    if v.Validate() {
        fmt.Println("Validation passed")
    } else {
        fmt.Println(v.Errors)
    }
    

Competitor Comparisons

16,709

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

Pros of validator

  • More widely adopted and mature project with a larger community
  • Extensive documentation and examples available
  • Supports custom validation functions and field-level validation

Cons of validator

  • Steeper learning curve due to more complex API
  • Heavier dependency with more features, which may be overkill for simpler projects

Code Comparison

validate:

type User struct {
    Name  string `validate:"required|minLen:5|maxLen:20"`
    Email string `validate:"required|email"`
    Age   int    `validate:"required|int|min:18|max:99"`
}

validator:

type User struct {
    Name  string `validate:"required,min=5,max=20"`
    Email string `validate:"required,email"`
    Age   int    `validate:"required,gte=18,lte=99"`
}

Both libraries offer similar functionality for struct validation, with slight differences in syntax. validate uses pipe-separated rules, while validator uses comma-separated rules. validator's syntax is more concise, but validate's may be more readable for complex validations.

validate provides a simpler API and lighter footprint, making it easier to get started with and potentially more suitable for smaller projects. However, validator offers more advanced features and customization options, which can be beneficial for larger, more complex applications.

Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.

Pros of govalidator

  • Simpler API with a more straightforward approach to validation
  • Supports custom error messages for each validation rule
  • Includes built-in sanitization functions for data cleaning

Cons of govalidator

  • Less extensive set of built-in validation rules compared to validate
  • Limited support for nested struct validation
  • Fewer options for customizing validation behavior

Code Comparison

govalidator:

rules := govalidator.MapData{
    "name":  []string{"required", "between:3,50"},
    "email": []string{"required", "email"},
}
messages := govalidator.MapData{
    "name": []string{"required:Name is required"},
}

validate:

v := validate.Struct(&user{
    Name:  "john",
    Email: "john@example.com",
})
v.AddRule("name", "required|minLen:3|maxLen:50")
v.AddRule("email", "required|email")

Both libraries offer validation for Go applications, but they differ in their approach and feature set. govalidator provides a simpler API with built-in sanitization, while validate offers more extensive validation rules and better support for nested structs. The choice between the two depends on the specific requirements of your project and personal preference for API design.

An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.

Pros of ozzo-validation

  • More mature and widely adopted project with a larger community
  • Supports custom validation rules and error messages
  • Offers built-in validation for common Go types (e.g., slices, maps)

Cons of ozzo-validation

  • Slightly more verbose syntax for defining validation rules
  • Less frequent updates and maintenance compared to validate

Code Comparison

validate:

v := validate.Struct(user)
v.StringRule("Name", "required|minLen:5|maxLen:20")
v.StringRule("Email", "required|email")

ozzo-validation:

err := validation.ValidateStruct(&user,
    validation.Field(&user.Name, validation.Required, validation.Length(5, 20)),
    validation.Field(&user.Email, validation.Required, is.Email),
)

Both libraries offer similar functionality for struct validation, but validate uses a more concise string-based rule definition, while ozzo-validation employs a more explicit, function-based approach. validate's syntax may be easier to read at a glance, but ozzo-validation's method allows for more flexibility and type safety.

Overall, ozzo-validation is a solid choice for projects requiring a battle-tested validation library with extensive features. However, validate offers a more lightweight alternative with a simpler syntax, making it suitable for smaller projects or those prioritizing ease of use.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Validate

GitHub tag (latest SemVer) GoDoc GitHub go.mod Go version Coverage Status Go Report Card Actions Status

validate is a generic Go data validate and filter tool library.

  • Support quick validate Map, Struct, Request(Form, JSON, url.Values, UploadedFile) data
    • Validating http.Request automatically collects data based on the request Content-Type value
    • Supports checking each child value in a slice. eg: v.StringRule("tags.*", "required|string")
  • Support filter/sanitize/convert data before validate
  • Support add custom filter/validator func
  • Support scene settings, verify different fields in different scenes
  • Support custom error messages, field translates.
    • Can use message, label tags in struct
  • Customizable i18n aware error messages, built in en, zh-CN, zh-TW
  • Built-in common data type filter/converter. see Built In Filters
  • Many commonly used validators have been built in(> 70), see Built In Validators
  • Can use validate in any frameworks, such as Gin, Echo, Chi and more
  • Supports direct use of rules to validate value. eg: validate.Val("xyz@mail.com", "required|email")

中文说明

中文说明请查看 README.zh-CN

Go Doc

Validate Struct

Use the validate tag of the structure, you can quickly config a structure.

Config the struct use tags

Field translations and error messages for structs can be quickly configured using the message and label tags.

  • Support configuration field mapping through structure tag, read the value of json tag by default
  • Support configuration error message via structure's message tag
  • Support configuration field translation via structure's label tag
package main

import (
	"fmt"
	"time"

	"github.com/gookit/validate"
)

// UserForm struct
type UserForm struct {
	Name     string    `validate:"required|min_len:7" message:"required:{field} is required" label:"User Name"`
	Email    string    `validate:"email" message:"email is invalid" label:"User Email"`
	Age      int       `validate:"required|int|min:1|max:99" message:"int:age must int|min:age min value is 1"`
	CreateAt int       `validate:"min:1"`
	Safe     int       `validate:"-"`
	UpdateAt time.Time `validate:"required" message:"update time is required"`
	Code     string    `validate:"customValidator"`
	// ExtInfo nested struct
	ExtInfo struct{
		Homepage string `validate:"required" label:"Home Page"`
		CityName string
	} `validate:"required" label:"Home Page"`
}

// CustomValidator custom validator in the source struct.
func (f UserForm) CustomValidator(val string) bool {
	return len(val) == 4
}

Config validate use struct methods

validate provides extended functionality:

The struct can implement three interfaces methods, which is convenient to do some customization:

  • ConfigValidation(v *Validation) will be called after the validator instance is created
  • Messages() map[string]string can customize the validator error message
  • Translates() map[string]string can customize field translation
package main

import (
	"fmt"
	"time"

	"github.com/gookit/validate"
)

// UserForm struct
type UserForm struct {
	Name     string    `validate:"required|min_len:7"`
	Email    string    `validate:"email"`
	Age      int       `validate:"required|int|min:1|max:99"`
	CreateAt int       `validate:"min:1"`
	Safe     int       `validate:"-"`
	UpdateAt time.Time `validate:"required"`
	Code     string    `validate:"customValidator"`
	// ExtInfo nested struct
	ExtInfo struct{
		Homepage string `validate:"required"`
		CityName string
	} `validate:"required"`
}

// CustomValidator custom validator in the source struct.
func (f UserForm) CustomValidator(val string) bool {
	return len(val) == 4
}

// ConfigValidation config the Validation
// eg:
// - define validate scenes
func (f UserForm) ConfigValidation(v *validate.Validation) {
	v.WithScenes(validate.SValues{
		"add":    []string{"ExtInfo.Homepage", "Name", "Code"},
		"update": []string{"ExtInfo.CityName", "Name"},
	})
}

// Messages you can custom validator error messages. 
func (f UserForm) Messages() map[string]string {
	return validate.MS{
		"required": "oh! the {field} is required",
		"email": "email is invalid",
		"Name.required": "message for special field",
		"Age.int": "age must int",
		"Age.min": "age min value is 1",
	}
}

// Translates you can custom field translates. 
func (f UserForm) Translates() map[string]string {
	return validate.MS{
		"Name": "User Name",
		"Email": "User Email",
		"ExtInfo.Homepage": "Home Page",
	}
}

Create and validating

Can use validate.Struct(ptr) quick create a validation instance. then call v.Validate() for validating.

package main

import (
  "fmt"

  "github.com/gookit/validate"
)

func main() {
	u := &UserForm{
		Name: "inhere",
	}
	
	v := validate.Struct(u)
	// v := validate.New(u)

	if v.Validate() { // validate ok
		// do something ...
	} else {
		fmt.Println(v.Errors) // all error messages
		fmt.Println(v.Errors.One()) // returns a random error message text
		fmt.Println(v.Errors.OneError()) // returns a random error
		fmt.Println(v.Errors.Field("Name")) // returns error messages of the field 
	}
}

Validate Map

You can also validate a MAP data directly.

package main

import (
"fmt"

"github.com/gookit/validate"
)

func main()  {
	m := map[string]any{
		"name":  "inhere",
		"age":   100,
		"oldSt": 1,
		"newSt": 2,
		"email": "some@email.com",
		"tags": []string{"go", "php", "java"},
	}

	v := validate.Map(m)
	// v := validate.New(m)
	v.AddRule("name", "required")
	v.AddRule("name", "minLen", 7)
	v.AddRule("age", "max", 99)
	v.AddRule("age", "min", 1)
	v.AddRule("email", "email")
	
	// can also
	v.StringRule("age", "required|int|min:1|max:99")
	v.StringRule("name", "required|minLen:7")
	v.StringRule("tags", "required|slice|minlen:1")
	// feat: support check sub-item in slice
	v.StringRule("tags.*", "required|string|min_len:7")

	// v.WithScenes(map[string]string{
	//	 "create": []string{"name", "email"},
	//	 "update": []string{"name"},
	// })
	
	if v.Validate() { // validate ok
		safeData := v.SafeData()
		// do something ...
	} else {
		fmt.Println(v.Errors) // all error messages
		fmt.Println(v.Errors.One()) // returns a random error message text
	}
}

Validate Request

If it is an HTTP request, you can quickly validate the data and pass the verification. Then bind the secure data to the structure.

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gookit/validate"
)

// UserForm struct
type UserForm struct {
	Name     string
	Email    string
	Age      int
	CreateAt int
	Safe     int
	UpdateAt time.Time
	Code     string
}

func main()  {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		data, err := validate.FromRequest(r)
		if err != nil {
			panic(err)
		}

		v := data.Create()
		// setting rules
		v.FilterRule("age", "int") // convert value to int
		
		v.AddRule("name", "required")
		v.AddRule("name", "minLen", 7)
		v.AddRule("age", "max", 99)
		v.StringRule("code", `required|regex:\d{4,6}`)

		if v.Validate() { // validate ok
			// safeData := v.SafeData()
			userForm := &UserForm{}
			v.BindSafeData(userForm)

			// do something ...
			fmt.Println(userForm.Name)
		} else {
			fmt.Println(v.Errors) // all error messages
			fmt.Println(v.Errors.One()) // returns a random error message text
		}
	})

	http.ListenAndServe(":8090", handler)
}

Quick Method

Quick create Validation instance.

  • New(data any, scene ...string) *Validation
  • Request(r *http.Request) *Validation
  • JSON(s string, scene ...string) *Validation
  • Struct(s any, scene ...string) *Validation
  • Map(m map[string]any, scene ...string) *Validation

Quick create DataFace instance.

  • FromMap(m map[string]any) *MapData
  • FromStruct(s any) (*StructData, error)
  • FromJSON(s string) (*MapData, error)
  • FromJSONBytes(bs []byte) (*MapData, error)
  • FromURLValues(values url.Values) *FormData
  • FromRequest(r *http.Request, maxMemoryLimit ...int64) (DataFace, error)

Create Validation from DataFace

d := FromMap(map[string]any{"key": "val"})
v := d.Validation()

Methods In Validation

  • func (v *Validation) Validate(scene ...string) bool Do validating and return is success.
  • func (v *Validation) ValidateE(scene ...string) Errors Do validating and return error.

More Usage

Validate Error

v.Errors is map data, top key is field name, value is map[string]string.

// do validating
if v.Validate() {
	return nil
}

// get errors
es := v.Errors

// check
es.Empty() // bool

// returns an random error, if no error returns nil
fmt.Println(v.Errors.OneError())
fmt.Println(v.Errors.ErrOrNil())

fmt.Println(v.Errors) // all error messages
fmt.Println(v.Errors.One()) // returns a random error message text
fmt.Println(v.Errors.Field("Name")) // returns error messages of the field 

Encode to JSON:

  • StopOnError=true(default), will only one error
{
    "field1": {
        "required": "error msg0"
    }
}
  • if StopOnError=false, will get multi error
{
    "field1": {
        "minLen": "error msg1",
        "required": "error msg0"
    },
    "field2": {
        "min": "error msg2"
    }
}

Global Option

You can adjust some processing logic of the validator by changing the global option settings.

// GlobalOption settings for validate
type GlobalOption struct {
	// FilterTag name in the struct tags.
	//
	// default: filter
	FilterTag string
	// ValidateTag in the struct tags.
	//
	// default: validate
	ValidateTag string
	// FieldTag the output field name in the struct tags.
	// it as placeholder on error message.
	//
	// default: json
	FieldTag string
	// LabelTag the display name in the struct tags.
	// use for define field translate name on error.
	//
	// default: label
	LabelTag string
	// MessageTag define error message for the field.
	//
	// default: message
	MessageTag string
	// StopOnError If true: An error occurs, it will cease to continue to verify
	StopOnError bool
	// SkipOnEmpty Skip check on field not exist or value is empty
	SkipOnEmpty bool
	// UpdateSource Whether to update source field value, useful for struct validate
	UpdateSource bool
	// CheckDefault Whether to validate the default value set by the user
	CheckDefault bool
	// CheckZero Whether validate the default zero value. (intX,uintX: 0, string: "")
	CheckZero bool
	// CheckSubOnParentMarked True: only collect sub-struct rule on current field has rule.
	CheckSubOnParentMarked bool
	// ValidatePrivateFields Whether to validate private fields or not, especially when inheriting other other structs.
	//
	//  type foo struct {
	//	  Field int `json:"field" validate:"required"`
	//  }
	//  type bar struct {
	//    foo // <-- validate this field
	//    Field2 int `json:"field2" validate:"required"`
	//  }
	//
	// default: false
	ValidatePrivateFields bool
}

Usage:

// change global opts
validate.Config(func(opt *validate.GlobalOption) {
	opt.StopOnError = false
	opt.SkipOnEmpty = false
})

Validating Private (Unexported fields)

By default, private fields are skipped. It is not uncommon to find code such as the following

type foo struct {
	somefield int
}

type Bar struct {
	foo
	SomeOtherField string
}

In order to have foo.somefield validated, enable the behavior by setting GlobalOption.ValidatePrivateFields to true.

validate.Config(func(opt *validate.GlobalOption) {
	opt.ValidatePrivateFields = true
})

Custom Error Messages

  • Register language messages
import "github.com/gookit/validate/locales/zhcn"

// for all Validation.
// NOTICE: must be registered before on validate.New(), it only need call at once.
zhcn.RegisterGlobal()

// ... ...

v := validate.New()

// only for current Validation
zhcn.Register(v)
  • Manual add global messages
validate.AddGlobalMessages(map[string]string{
    "minLength": "OO! {field} min length is %d",
})
  • Add messages for current validation
v := validate.New(map[string]any{
    "name": "inhere",
})
v.StringRule("name", "required|string|minLen:7|maxLen:15")

v.AddMessages(map[string]string{
    "minLength": "OO! {field} min length is %d",
    "name.minLen": "OO! username min length is %d",
})
  • Use struct tags: message, label
type UserForm struct {
    Name  string `validate:"required|minLen:7" label:"User Name"`
    Email string `validate:"email" message:"email is invalid" label:"User Email"`
}
  • Use struct method Messages()
// Messages you can custom validator error messages. 
func (f UserForm) Messages() map[string]string {
	return validate.MS{
		"required": "oh! the {field} is required",
		"Name.required": "message for special field",
	}
}

Add Custom Validator

validate supports adding custom validators, and supports adding global validator and temporary validator.

  • Global Validator is globally valid and can be used everywhere
  • Temporary Validator added to the current validation instance, only the current validation is available
  • Add verification method to the structure. How to use please see the structure verification example above

Note: The validator method must return a bool to indicate whether the validation was successful. The first parameter is the corresponding field value. If there are additional parameters, they will be appended automatically.

Add Global Validator

You can add one or more custom validators at once.

validate.AddValidator("myCheck0", func(val any) bool {
	// do validate val ...
	return true
})
validate.AddValidators(validate.M{
	"myCheck1": func(val any) bool {
		// do validate val ...
		return true
	},
})

Add Temporary Validator

Again, you can add one or more custom validators at once.

v := validate.Struct(u)
v.AddValidator("myFunc3", func(val any) bool {
	// do validate val ...
	return true
})
v.AddValidators(validate.M{
	"myFunc4": func(val any) bool {
		// do validate val ...
		return true
	},
})

Add Custom Filter

validate can also support adding custom filters, and supports adding global filter and temporary filter.

  • Global Filter is globally valid and can be used everywhere
  • Temporary Filter added to the current validation instance, only the current validation is available

TIP: for filter func, we allow functions with 1 result or 2 results where the second is an error.

Add Global Filter

You can add one or more custom validators at once.

package main

import "github.com/gookit/validate"

func init() {
	validate.AddFilter("myToIntFilter0", func(val any) int {
		// do filtering val ...
		return 1
	})
	validate.AddFilters(validate.M{
		"myToIntFilter1": func(val any) (int, error) {
			// do filtering val ...
			return 1, nil
		},
	})
}

Add Temporary Filter

Again, you can add one or more custom filters at once.

package main

import "github.com/gookit/validate"

func main() {
	v := validate.New(&someStrcut{})

	v.AddFilter("myToIntFilter0", func(val any) int {
		// do filtering val ...
		return 1
	})
	v.AddFilters(validate.M{
		"myToIntFilter1": func(val any) (int, error) {
			// do filtering val ...
			return 1, nil
		},
	})
	// use the added filter
	v.FilterRule("field", "myToIntFilter0")
}

Custom required validation

Allows a custom required validator to customize whether the validation is empty. However, note that the validator name must start with required, e.g. required_custom.

	type Data struct {
		Age  int    `validate:"required_custom" message:"age is required"`
		Name string `validate:"required"`
	}

	v := validate.New(&Data{
		Name: "tom",
		Age:  0,
	})

	v.AddValidator("required_custom", func(val any) bool {
		// do check value
		return false
	})

	ok := v.Validate()
	assert.False(t, ok)

Use on gin framework

Can use validate in any frameworks, such as Gin, Echo, Chi and more.

Examples on gin:

package main
import (
    "github.com/gin-gonic/gin/binding"
    "github.com/gookit/validate"
)

// implements the binding.StructValidator
type customValidator struct {}

func (c *customValidator) ValidateStruct(ptr any) error {
    v := validate.Struct(ptr)
    v.Validate() // do validating
    
    if v.Errors.Empty() {
	return nil
    }

    return v.Errors
}

func (c *customValidator) Engine() any {
    return nil
}

func main()  {
	// ...

    // after init gin, set custom validator
    binding.Validator = &customValidator{}
}

Built In Validators

Camel-style validator names now have underlined aliases. endsWith can also be written as ends_with

validator/aliasesdescription
requiredCheck value is required and cannot be empty.
required_if/requiredIfrequired_if:anotherfield,value,... The field under validation must be present and not empty if the anotherField field is equal to any value.
requiredUnlessrequired_unless:anotherfield,value,... The field under validation must be present and not empty unless the anotherField field is equal to any value.
requiredWithrequired_with:foo,bar,... The field under validation must be present and not empty only if any of the other specified fields are present.
requiredWithAllrequired_with_all:foo,bar,... The field under validation must be present and not empty only if all of the other specified fields are present.
requiredWithoutrequired_without:foo,bar,... The field under validation must be present and not empty only when any of the other specified fields are not present.
requiredWithoutAllrequired_without_all:foo,bar,... The field under validation must be present and not empty only when all of the other specified fields are not present.
-/safeThe field values are safe and do not require validation
int/integer/isIntCheck value is intX uintX type, And support size checking. eg: "int" "int:2" "int:2,12"
uint/isUintCheck value is uint(uintX) type, value >= 0
bool/isBoolCheck value is bool string(true: "1", "on", "yes", "true", false: "0", "off", "no", "false").
string/isStringCheck value is string type.
float/isFloatCheck value is float(floatX) type
slice/isSliceCheck value is slice type([]intX []uintX []byte []string ...).
in/enumCheck if the value is in the given enumeration "in:a,b"
not_in/notInCheck if the value is not in the given enumeration "contains:b"
containsCheck if the input value contains the given value
not_contains/notContainsCheck if the input value not contains the given value
string_contains/stringContainsCheck if the input string value is contains the given sub-string
starts_with/startsWithCheck if the input string value is starts with the given sub-string
ends_with/endsWithCheck if the input string value is ends with the given sub-string
range/betweenCheck that the value is a number and is within the given range
max/lteCheck value is less than or equal to the given value
min/gteCheck value is greater than or equal to the given value(for intX uintX floatX)
eq/equal/isEqualCheck that the input value is equal to the given value
ne/notEq/notEqualCheck that the input value is not equal to the given value
lt/lessThanCheck value is less than the given value(use for intX uintX floatX)
gt/greaterThanCheck value is greater than the given value(use for intX uintX floatX)
email/isEmailCheck value is email address string.
intEq/intEqualCheck value is int and equals to the given value.
len/lengthCheck value length is equals to the given size(use for string array slice map).
regex/regexpCheck if the value can pass the regular verification
arr/list/array/isArrayCheck value is array, slice type
map/isMapCheck value is a MAP type
strings/isStringsCheck value is string slice type(only allow []string).
ints/isIntsCheck value is int slice type(only allow []int).
min_len/minLen/minLengthCheck the minimum length of the value is the given size
max_len/maxLen/maxLengthCheck the maximum length of the value is the given size
eq_field/eqFieldCheck that the field value is equals to the value of another field
ne_field/neFieldCheck that the field value is not equals to the value of another field
gte_field/gteFieldCheck that the field value is greater than or equal to the value of another field
gt_field/gtFieldCheck that the field value is greater than the value of another field
lte_field/lteFieldCheck if the field value is less than or equal to the value of another field
lt_field/ltFieldCheck that the field value is less than the value of another field
file/isFileVerify if it is an uploaded file
image/isImageCheck if it is an uploaded image file and support suffix check
mime/mimeType/inMimeTypesCheck that it is an uploaded file and is in the specified MIME type
date/isDateCheck the field value is date string. eg 2018-10-25
gt_date/gtDate/afterDateCheck that the input value is greater than the given date string.
lt_date/ltDate/beforeDateCheck that the input value is less than the given date string
gte_date/gteDate/afterOrEqualDateCheck that the input value is greater than or equal to the given date string.
lte_date/lteDate/beforeOrEqualDateCheck that the input value is less than or equal to the given date string.
has_whitespace/hasWhitespaceCheck value string has Whitespace.
ascii/ASCII/isASCIICheck value is ASCII string.
alpha/isAlphaVerify that the value contains only alphabetic characters
alphaNum/isAlphaNumCheck that only letters, numbers are included
alphaDash/isAlphaDashCheck to include only letters, numbers, dashes ( - ), and underscores ( _ )
multiByte/isMultiByteCheck value is MultiByte string.
base64/isBase64Check value is Base64 string.
dns_name/dnsName/DNSName/isDNSNameCheck value is DNSName string.
data_uri/dataURI/isDataURICheck value is DataURI string.
empty/isEmptyCheck value is Empty string.
hex_color/hexColor/isHexColorCheck value is Hex color string.
hexadecimal/isHexadecimalCheck value is Hexadecimal string.
json/JSON/isJSONCheck value is JSON string.
lat/latitude/isLatitudeCheck value is Latitude string.
lon/longitude/isLongitudeCheck value is Longitude string.
mac/isMACCheck value is MAC string.
num/number/isNumberCheck value is number string. >= 0
cn_mobile/cnMobile/isCnMobileCheck value is china mobile number string.
printableASCII/isPrintableASCIICheck value is PrintableASCII string.
rgb_color/rgbColor/RGBColor/isRGBColorCheck value is RGB color string.
url/isURLCheck value is URL string.
fullUrl/isFullURLCheck value is full URL string(must start with http,https).
ip/isIPCheck value is IP(v4 or v6) string.
ipv4/isIPv4Check value is IPv4 string.
ipv6/isIPv6Check value is IPv6 string.
CIDR/isCIDRCheck value is CIDR string.
CIDRv4/isCIDRv4Check value is CIDRv4 string.
CIDRv6/isCIDRv6Check value is CIDRv6 string.
uuid/isUUIDCheck value is UUID string.
uuid3/isUUID3Check value is UUID3 string.
uuid4/isUUID4Check value is UUID4 string.
uuid5/isUUID5Check value is UUID5 string.
filePath/isFilePathCheck value is an existing file path
unixPath/isUnixPathCheck value is Unix Path string.
winPath/isWinPathCheck value is Windows Path string.
isbn10/ISBN10/isISBN10Check value is ISBN10 string.
isbn13/ISBN13/isISBN13Check value is ISBN13 string.

Notice:

  • intX is contains: int, int8, int16, int32, int64
  • uintX is contains: uint, uint8, uint16, uint32, uint64
  • floatX is contains: float32, float64

Built In Filters

Filters powered by: gookit/filter

filter/aliasesdescription
int/toIntConvert value(string/intX/floatX) to int type v.FilterRule("id", "int")
uint/toUintConvert value(string/intX/floatX) to uint type v.FilterRule("id", "uint")
int64/toInt64Convert value(string/intX/floatX) to int64 type v.FilterRule("id", "int64")
float/toFloatConvert value(string/intX/floatX) to float type
bool/toBoolConvert string value to bool. (true: "1", "on", "yes", "true", false: "0", "off", "no", "false")
trim/trimSpaceClean up whitespace characters on both sides of the string
ltrim/trimLeftClean up whitespace characters on left sides of the string
rtrim/trimRightClean up whitespace characters on right sides of the string
int/integerConvert value(string/intX/floatX) to int type v.FilterRule("id", "int")
lower/lowercaseConvert string to lowercase
upper/uppercaseConvert string to uppercase
lcFirst/lowerFirstConvert the first character of a string to lowercase
ucFirst/upperFirstConvert the first character of a string to uppercase
ucWord/upperWordConvert the first character of each word to uppercase
camel/camelCaseConvert string to camel naming style
snake/snakeCaseConvert string to snake naming style
escapeJs/escapeJSEscape JS string.
escapeHtml/escapeHTMLEscape HTML string.
str2ints/strToIntsConvert string to int slice []int
str2time/strToTimeConvert date string to time.Time.
str2arr/str2array/strToArrayConvert string to string slice []string

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli build CLI application, tool library, running CLI commands
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More please see https://github.com/gookit

See also

License

MIT