Popularity
3.1
Growing
Activity
5.1
-
50
7
7
Programming language: Go
License: MIT License
Tags:
Validation
Latest version: v1.2.0
govalid alternatives and similar packages
Based on the "Validation" category.
Alternatively, view govalid alternatives based on common mentions on social networks and blogs.
-
validator
:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving -
ozzo-validation
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags. -
Validate
⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器,支持自定义验证器、自定义消息、字段翻译。
CodeRabbit: AI Code Reviews for Developers
Revolutionize your code reviews with AI. CodeRabbit offers PR summaries, code walkthroughs, 1-click suggestions, and AST-based analysis. Boost productivity and code quality across all major languages with each PR.
Promo
coderabbit.ai
Do you think we are missing an alternative of govalid or a related project?
README
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() {
// 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)
})
v.Register(Post{}) // Register all structs at load time
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.