Struct validation using tags

Govalid

Use Govalid to validate structs.

Documentation

For full documentation see pkg.go.dev.

Example

package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/twharmon/govalid"
)

type Post struct {
	// ID has no constraints
	ID int

	// Title is required, must be at least 3 characters long, cannot be
	// more than 20 characters long, and must match ^[a-zA-Z ]+$
	Title string `govalid:"req|min:3|max:20|regex:^[a-zA-Z ]+$"`

	// Body is not required, cannot be more than 10000 charachers,
	// and must be "fun" (a custom rule defined below).
	Body string `govalid:"max:10000|fun"`

	// Category is not required, but if not zero value ("") it must be
	// either "announcement" or "bookreview".
	Category string `govalid:"in:announcement,bookreview"`
}

var v = govalid.New()

func main() {
	v.Register(Post{}) // Register all structs at load time

	// Add Custom validation to the struct `Post`
	v.AddCustom(Post{}, func(val interface{}) string {
		post := val.(*Post)
		if post.Category != "" && !strings.Contains(post.Body, post.Category) {
			return fmt.Sprintf("Body must contain %s", post.Category)
		}
		return ""
	})

	// Add custom string "fun" that can be used on any string field
	// in any struct.
	v.AddCustomStringRule("fun", func(field string, value string) string {
		if float64(strings.Count(value, "!")) / float64(utf8.RuneCountInString(value)) > 0.001 {
			return ""
		}
		return fmt.Sprintf("%s must contain more exclamation marks", field)
	})

	p := Post{
		ID:       5,
		Title:    "Hi",
		Body:     "Hello world!",
		Category: "announcement",
	}

	vio, err := v.Violations(&p)
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println(vio)
}

Benchmarks

BenchmarkValidatorStringReqInvalid	         192 ns/op	      48 B/op	       3 allocs/op
BenchmarkValidatorStringReqValid	        98.5 ns/op	      16 B/op	       1 allocs/op
BenchmarkValidatorsVariety	                1114 ns/op	     281 B/op	      13 allocs/op

Contribute

Make a pull request.

Similar Resources

Gin Middleware to extract json tag value from playground validator's errors validation

Json Tag Extractor for Go-Playground Validator This is Gin Middleware that aim to extract json tag and than store it to FieldError.Field() object. Ins

Jan 14, 2022

Validator - Replace the validation framework used by gin

validator Replace the validation framework used by gin replace mod:replace githu

Jan 18, 2022

:balloon: A lightweight struct validator for Go

gody Go versions supported Installation go get github.com/guiferpa/gody/v2 Usage package main import ( "encoding/json" "fmt" "net/http"

Nov 19, 2022

Struct validation using tags

Govalid Use Govalid to validate structs. Documentation For full documentation see pkg.go.dev. Example package main import ( "fmt" "log" "strings"

Dec 6, 2022

Match regex group into go struct using struct tags and automatic parsing

regroup Simple library to match regex expression named groups into go struct using struct tags and automatic parsing Installing go get github.com/oris

Nov 5, 2022

Pagser is a simple, extensible, configurable parse and deserialize html page to struct based on goquery and struct tags for golang crawler

Pagser is a simple, extensible, configurable parse and deserialize html page to struct based on goquery and struct tags for golang crawler

Pagser Pagser inspired by page parser。 Pagser is a simple, extensible, configurable parse and deserialize html page to struct based on goquery and str

Dec 13, 2022

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

Package validator Package validator implements value validations for structs and individual fields based on tags. It has the following unique features

Jan 1, 2023

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

Package validator implements value validations for structs and individual fields based on tags.

Nov 9, 2022

AWS Tags Updater - Sync tags with all resources via sheet 🐏🐏

AWS Tags Updater - Sync tags with all resources via sheet 🐏🐏

Mar 22, 2022

☄ The golang convenient converter supports Database to Struct, SQL to Struct, and JSON to Struct.

☄ The golang convenient converter supports Database to Struct, SQL to Struct, and JSON to Struct.

Gormat - Cross platform gopher tool The golang convenient converter supports Database to Struct, SQL to Struct, and JSON to Struct. 中文说明 Features Data

Dec 20, 2022

Golang parameter validation, which can replace go-playground/validator, includes ncluding Cross Field, Map, Slice and Array diving, provides readable,flexible, configurable validation.

Golang parameter validation, which can replace go-playground/validator, includes ncluding Cross Field, Map, Slice and Array diving, provides readable,flexible, configurable validation.

Checker 中文版本 Checker is a parameter validation package, can be use in struct/non-struct validation, including cross field validation in struct, elemen

Dec 16, 2022

Automatically sets up command line flags based on struct fields and tags.

Automatically sets up command line flags based on struct fields and tags.

Commandeer Commandeer sets up command line flags based on struct fields and tags. Do you... like to develop Go apps as libraries with tiny main packag

Dec 1, 2022

Trims, sanitizes & scrubs data based on struct tags (go, golang)

Conform- keep user input in check (go, golang) Trim, sanitize, and modify struct string fields in place, based on tags. Update Jan 12, 2016 -- Now als

Dec 20, 2022

A Go library for parsing struct tags from environment variables.

Envconfig Envconfig populates struct field values based on environment variables or arbitrary lookup functions. It supports pre-setting mutations, whi

Jan 2, 2023

Go tool to modify struct field tags

Go tool to modify struct field tags

Go tool to modify/update field tags in structs. gomodifytags makes it easy to update, add or delete the tags in a struct field. You can easily add new tags, update existing tags (such as appending a new key, i.e: db, xml, etc..) or remove existing tags

Jan 1, 2023

goql is a GraphQL client package written in Go. with built-in two-way marshaling support via struct tags.

goql is a GraphQL client package written in Go. with built-in two-way marshaling support via struct tags.

Dec 1, 2022

A linter that handles struct tags.

Tagliatelle A linter that handles struct tags. Supported string casing: camel pascal kebab snake goCamel Respects Go's common initialisms (e.g. HttpRe

Dec 15, 2022

Align Golang struct tags

Formattag The tool is used to align golang struct's tags. eg.: Before // TestStruct this is a test struct type TestStruct struct { ID stri

Aug 1, 2022

Automatically generate tags for golang struct.

gtag is a command tool that can automatically generate tags for golang struct. Quick start Install gtag into your GOPATH go install github.com/sycki/g

Feb 12, 2022
Comments
  • Lazy registration

    Lazy registration

    Remove the need to call Register at load time. This makes the package much easier to use and does so without any significant cost. The registration will occur the first time the struct is encountered.

  • Wrong Docs

    Wrong Docs

    The problem is, that the example code does not run correctly, because the rule "fun" can not be found. The response is empty, but with this extra line in the register function I´m able to see the issue:

    if err := v.registerField(m, typ.Field(i)); err != nil {
    	fmt.Println("err in if, err", err)
    	return err
    }
    

    Returns the following error: err in if, err invalid rule 'fun' found in govalid tag on Post

    All you have to do is to change the order of the registration and the adding of custom rules.

    I made a PR for this.

    Go version:

    go version go1.16.2 windows/amd64
    
  • Govalid with Pointer Types is not possible

    Govalid with Pointer Types is not possible

    The govalid struct validation is only for non pointer types. Is there any reason for that? I think there a some great possibilities for pointers with govalid tags.

    Is this already in planning? If not I can try to investigate further and maybe make a pull request

    go version go1.16.2 windows/amd64
    
:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

Package validator Package validator implements value validations for structs and individual fields based on tags. It has the following unique features

Jan 1, 2023
Golang parameter validation, which can replace go-playground/validator, includes ncluding Cross Field, Map, Slice and Array diving, provides readable,flexible, configurable validation.
Golang parameter validation, which can replace go-playground/validator, includes ncluding Cross Field, Map, Slice and Array diving, provides readable,flexible, configurable validation.

Checker 中文版本 Checker is a parameter validation package, can be use in struct/non-struct validation, including cross field validation in struct, elemen

Dec 16, 2022
Dec 28, 2022
An interesting go struct tag expression syntax for field validation, etc.

go-tagexpr An interesting go struct tag expression syntax for field validation, etc. Usage Validator: A powerful validator that supports struct tag ex

Jan 9, 2023
Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.
Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.

Validate golang request data with simple rules. Highly inspired by Laravel's request validation. Installation Install the package using $ go get githu

Dec 29, 2022
Swagger builder and input validation for Go servers
Swagger builder and input validation for Go servers

crud A Swagger/OpenAPI builder and validation library for building HTTP/REST APIs. Heavily inspired by hapi and the hapi-swagger projects. No addition

Jan 5, 2023
Go package containing implementations of efficient encoding, decoding, and validation APIs.

encoding Go package containing implementations of encoders and decoders for various data formats. Motivation At Segment, we do a lot of marshaling and

Dec 25, 2022
Library providing opanapi3 and Go types for store/validation and transfer of ISO-4217, ISO-3166, and other types.

go-types This library has been created with the purpose to facilitate the store, validation, and transfer of Go ISO-3166/ISO-4217/timezones/emails/URL

Nov 9, 2022
Opinionated go to validation library

?? valeed Your opinionated go-to validation library. Struct tag-based. Validate here, validate there, validate everywhere. Sleek and simple validation

Jul 21, 2022
Simple module for validation inn control number

simple module for validation inn control number

Sep 4, 2022