Convert Figma logo to code with AI

thedevsaddam logogovalidator

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

1,310
124
1,310
43

Top Related Projects

16,499

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

[Go] Package of validators and sanitizers for strings, numerics, slices and structs

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

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

Quick Overview

Govalidator is a powerful and flexible validation library for Go (Golang). It provides a simple and intuitive way to validate structs, maps, and individual values using predefined rules or custom validation functions. The library supports both synchronous and asynchronous validation, making it suitable for various use cases.

Pros

  • Extensive set of built-in validation rules
  • Support for custom validation functions
  • Easy to use with structs, maps, and individual values
  • Asynchronous validation support for improved performance

Cons

  • Limited documentation for advanced use cases
  • Some users report occasional inconsistencies in error messages
  • Lack of built-in localization support for error messages

Code Examples

  1. Validating a struct:
type User struct {
    Username string `json:"username" validate:"required,alpha_num"`
    Email    string `json:"email" validate:"required,email"`
    Age      int    `json:"age" validate:"required,numeric,min:18"`
}

user := User{Username: "john_doe", Email: "invalid-email", Age: 16}
rules := govalidator.MapData{
    "username": []string{"required", "alpha_num"},
    "email":    []string{"required", "email"},
    "age":      []string{"required", "numeric", "min:18"},
}

v := govalidator.New(rules)
e := v.Validate(user)
fmt.Println(e)
  1. Validating a map:
data := map[string]interface{}{
    "name":  "John Doe",
    "email": "john@example.com",
    "age":   25,
}

rules := govalidator.MapData{
    "name":  []string{"required", "between:3,50"},
    "email": []string{"required", "email"},
    "age":   []string{"required", "numeric", "min:18"},
}

v := govalidator.New(rules)
e := v.ValidateMap(data)
fmt.Println(e)
  1. Custom validation function:
func validateEven(field string, rule string, message string, value interface{}) error {
    val, ok := value.(int)
    if !ok {
        return fmt.Errorf("The %s field must be an integer", field)
    }
    if val%2 != 0 {
        return fmt.Errorf("The %s field must be an even number", field)
    }
    return nil
}

govalidator.AddCustomRule("even", validateEven)

rules := govalidator.MapData{
    "number": []string{"required", "numeric", "even"},
}

data := map[string]interface{}{"number": 5}
v := govalidator.New(rules)
e := v.ValidateMap(data)
fmt.Println(e)

Getting Started

To use govalidator in your Go project, follow these steps:

  1. Install the package:

    go get github.com/thedevsaddam/govalidator
    
  2. Import the package in your code:

    import "github.com/thedevsaddam/govalidator"
    
  3. Define your validation rules and use the appropriate validation method:

    rules := govalidator.MapData{
        "field_name": []string{"required", "alpha_num"},
    }
    v := govalidator.New(rules)
    e := v.Validate(yourData)
    
  4. Handle the validation errors as needed in your application.

Competitor Comparisons

16,499

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

Pros of validator

  • More comprehensive feature set, including custom validation functions and cross-field validation
  • Better performance, especially for large structs or complex validation rules
  • More active development and community support

Cons of validator

  • Steeper learning curve due to more complex API and advanced features
  • Potentially more verbose syntax for simple validation cases
  • Larger codebase and dependency footprint

Code Comparison

govalidator:

rules := govalidator.MapData{
    "name":  []string{"required", "between:3,50"},
    "email": []string{"required", "email"},
}
data := map[string]interface{}{
    "name":  "John Doe",
    "email": "john@example.com",
}
v := govalidator.New(rules)
e := v.ValidateMap(data)

validator:

type User struct {
    Name  string `validate:"required,min=3,max=50"`
    Email string `validate:"required,email"`
}
user := User{Name: "John Doe", Email: "john@example.com"}
validate := validator.New()
err := validate.Struct(user)

Both libraries provide robust validation capabilities for Go applications. govalidator offers a simpler API and is easier to get started with, while validator provides more advanced features and better performance for complex scenarios. The choice between them depends on the specific needs of your project and your preference for API style.

[Go] Package of validators and sanitizers for strings, numerics, slices and structs

Pros of govalidator (asaskevich)

  • More comprehensive set of validation functions, including date, credit card, and UUID validation
  • Better documentation and examples in the README
  • Supports custom error messages for each validation rule

Cons of govalidator (asaskevich)

  • Less flexible API for custom validation rules
  • Slower performance for large-scale validation tasks
  • More complex setup and usage compared to thedevsaddam's version

Code Comparison

govalidator (asaskevich):

type User struct {
    Name  string `valid:"required,alpha"`
    Email string `valid:"required,email"`
    Age   int    `valid:"required,range(1|120)"`
}

_, err := govalidator.ValidateStruct(user)

govalidator (thedevsaddam):

rules := govalidator.MapData{
    "name":  []string{"required", "alpha"},
    "email": []string{"required", "email"},
    "age":   []string{"required", "numeric_between:1,120"},
}

errors := govalidator.New(rules).Validate(data)

Both libraries offer struct and map-based validation, but asaskevich's version uses struct tags for defining rules, while thedevsaddam's version uses a separate rules map. The latter approach provides more flexibility in defining and modifying validation rules at runtime.

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 flexible and extensible validation rules
  • Better support for custom validation functions
  • Cleaner API for defining complex validation scenarios

Cons of ozzo-validation

  • Slightly steeper learning curve due to more advanced features
  • May be overkill for simple validation tasks
  • Less built-in rules compared to govalidator

Code Comparison

govalidator:

rules := govalidator.MapData{
    "name":  []string{"required", "between:3,50"},
    "email": []string{"required", "email"},
}
v := govalidator.New(rules)
e := v.ValidateJSON(r.Body)

ozzo-validation:

type User struct {
    Name  string
    Email string
}

func (u User) Validate() error {
    return validation.ValidateStruct(&u,
        validation.Field(&u.Name, validation.Required, validation.Length(3, 50)),
        validation.Field(&u.Email, validation.Required, is.Email),
    )
}

Both libraries offer robust validation capabilities for Go applications. govalidator provides a simpler approach with a focus on map-based rules, while ozzo-validation offers a more flexible and extensible system that integrates well with struct-based validation. The choice between them depends on the complexity of your validation requirements and your preferred coding style.

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

Pros of validate

  • More comprehensive validation rules and built-in functions
  • Supports custom error messages and translations
  • Better performance in handling large datasets

Cons of validate

  • Steeper learning curve due to more complex API
  • Less straightforward for simple validation tasks
  • Requires more setup for basic use cases

Code Comparison

govalidator:

rules := govalidator.MapData{
    "name":  []string{"required", "between:3,50"},
    "email": []string{"required", "email"},
}
data := map[string]interface{}{
    "name":  "John Doe",
    "email": "john@example.com",
}
v := govalidator.New(rules)
e := v.ValidateMap(data)

validate:

v := validate.Struct(&User{
    Name:  "John Doe",
    Email: "john@example.com",
})
v.StringRule("name", "required|minLen:3|maxLen:50")
v.StringRule("email", "required|email")
if v.Validate() {
    // validation passed
} else {
    fmt.Println(v.Errors)
}

Both libraries offer robust validation capabilities for Go applications. govalidator provides a simpler, more intuitive API for basic validation tasks, making it easier to get started. validate, on the other hand, offers more advanced features and better performance for complex validation scenarios, but with a steeper learning curve. The choice between the two depends on the specific requirements of your project and the level of complexity you need in your validation logic.

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

govalidator

Build Status Project status Go Report Card Coverage Status GoDoc License

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

Installation

Install the package using

$ go get github.com/thedevsaddam/govalidator
// or
$ go get gopkg.in/thedevsaddam/govalidator.v1

Usage

To use the package import it in your *.go code

import "github.com/thedevsaddam/govalidator"
// or
import "gopkg.in/thedevsaddam/govalidator.v1"

Example

Validate form-data, x-www-form-urlencoded and query params


package main

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/thedevsaddam/govalidator"
)

func handler(w http.ResponseWriter, r *http.Request) {
	rules := govalidator.MapData{
		"username": []string{"required", "between:3,8"},
		"email":    []string{"required", "min:4", "max:20", "email"},
		"web":      []string{"url"},
		"phone":    []string{"digits:11"},
		"agree":    []string{"bool"},
		"dob":      []string{"date"},
	}

	messages := govalidator.MapData{
		"username": []string{"required:আপনাকে অবশ্যই ইউজারনেম দিতে হবে", "between:ইউজারনেম অবশ্যই ৩-৮ অক্ষর হতে হবে"},
		"phone":    []string{"digits:ফোন নাম্বার অবশ্যই ১১ নম্বারের হতে হবে"},
	}

	opts := govalidator.Options{
		Request:         r,        // request object
		Rules:           rules,    // rules map
		Messages:        messages, // custom message map (Optional)
		RequiredDefault: true,     // all the field to be pass the rules
	}
	v := govalidator.New(opts)
	e := v.Validate()
	err := map[string]interface{}{"validationError": e}
	w.Header().Set("Content-type", "application/json")
	json.NewEncoder(w).Encode(err)
}

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("Listening on port: 9000")
	http.ListenAndServe(":9000", nil)
}

Send request to the server using curl or postman: curl GET "http://localhost:9000?web=&phone=&zip=&dob=&agree="

Response

{
    "validationError": {
        "agree": [
            "The agree may only contain boolean value, string or int 0, 1"
        ],
        "dob": [
            "The dob field must be a valid date format. e.g: yyyy-mm-dd, yyyy/mm/dd etc"
        ],
        "email": [
            "The email field is required",
            "The email field must be a valid email address"
        ],
        "phone": [
            "ফোন নাম্বার অবশ্যই ১১ নম্বারের হতে হবে"
        ],
        "username": [
            "আপনাকে অবশ্যই ইউজারনেম দিতে হবে",
            "ইউজারনেম অবশ্যই ৩-৮ অক্ষর হতে হবে"
        ],
        "web": [
            "The web field format is invalid"
        ]
    }
}

More examples

Validate file

Validate application/json or text/plain as raw body

Validate struct directly

Validation Rules

  • alpha The field under validation must be entirely alphabetic characters.
  • alpha_dash The field under validation may have alpha-numeric characters, as well as dashes and underscores.
  • alpha_space The field under validation may have alpha-numeric characters, as well as dashes, underscores and space.
  • alpha_num The field under validation must be entirely alpha-numeric characters.
  • between:numeric,numeric The field under validation check the length of characters/ length of array, slice, map/ range between two integer or float number etc.
  • numeric The field under validation must be entirely numeric characters.
  • numeric_between:numeric,numeric The field under validation must be a numeric value between the range. e.g: numeric_between:18,65 may contains numeric value like 35, 55 . You can also pass float value to check. Moreover, both bounds can be omitted to create an unbounded minimum (e.g: numeric_between:,65) or an unbounded maximum (e.g: numeric_between:-1,).
  • bool The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1" and "0".
  • credit_card The field under validation must have a valid credit card number. Accepted cards are Visa, MasterCard, American Express, Diners Club, Discover and JCB card
  • coordinate The field under validation must have a value of valid coordinate.
  • css_color The field under validation must have a value of valid CSS color. Accepted colors are hex, rgb, rgba, hsl, hsla like #909, #00aaff, rgb(255,122,122)
  • date The field under validation must have a valid date of format yyyy-mm-dd or yyyy/mm/dd.
  • date:dd-mm-yyyy The field under validation must have a valid date of format dd-mm-yyyy.
  • digits:int The field under validation must be numeric and must have an exact length of value.
  • digits_between:int,int The field under validation must be numeric and must have length between the range. e.g: digits_between:3,5 may contains digits like 2323, 12435
  • in:foo,bar The field under validation must have one of the values. e.g: in:admin,manager,user must contain the values (admin or manager or user)
  • not_in:foo,bar The field under validation must have one value except foo,bar. e.g: not_in:admin,manager,user must not contain the values (admin or manager or user)
  • email The field under validation must have a valid email.
  • float The field under validation must have a valid float number.
  • mac_address The field under validation must have be a valid Mac Address.
  • min:numeric The field under validation must have a min length of characters for string, items length for slice/map, value for integer or float. e.g: min:3 may contains characters minimum length of 3 like "john", "jane", "jane321" but not "mr", "xy"
  • max:numeric The field under validation must have a max length of characters for string, items length for slice/map, value for integer or float. e.g: max:6 may contains characters maximum length of 6 like "john doe", "jane doe" but not "john", "jane"
  • len:numeric The field under validation must have an exact length of characters, exact integer or float value, exact size of map/slice. e.g: len:4 may contains characters exact length of 4 like Food, Mood, Good
  • ip The field under validation must be a valid IP address.
  • ip_v4 The field under validation must be a valid IP V4 address.
  • ip_v6 The field under validation must be a valid IP V6 address.
  • json The field under validation must be a valid JSON string.
  • lat The field under validation must be a valid latitude.
  • lon The field under validation must be a valid longitude.
  • regex:regular expression The field under validation validate against the regex. e.g: regex:^[a-zA-Z]+$ validate the letters.
  • required The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true: 1) The value is null. 2)The value is an empty string. 3) Zero length of map, slice. 4) Zero value for integer or float
  • size:integer The field under validation validate a file size only in form-data (see example)
  • ext:jpg,png The field under validation validate a file extension (see example)
  • mime:image/jpg,image/png The field under validation validate a file mime type (see example)
  • url The field under validation must be a valid URL.
  • uuid The field under validation must be a valid UUID.
  • uuid_v3 The field under validation must be a valid UUID V3.
  • uuid_v4 The field under validation must be a valid UUID V4.
  • uuid_v5 The field under validation must be a valid UUID V5.

Add Custom Rules

func init() {
	// simple example
	govalidator.AddCustomRule("must_john", func(field string, rule string, message string, value interface{}) error {
		val := value.(string)
		if val != "john" || val != "John" {
			return fmt.Errorf("The %s field must be John or john", field)
		}
		return nil
	})

	// custom rules to take fixed length word.
	// e.g: word:5 will throw error if the field does not contain exact 5 word
	govalidator.AddCustomRule("word", func(field string, rule string, message string, value interface{}) error {
		valSlice := strings.Fields(value.(string))
		l, _ := strconv.Atoi(strings.TrimPrefix(rule, "word:")) //handle other error
		if len(valSlice) != l {
			return fmt.Errorf("The %s field must be %d word", field, l)
		}
		return nil
	})

}

Note: Array, map, slice can be validated by adding custom rules.

Custom Message/ Localization

If you need to translate validation message you can pass messages as options.

messages := govalidator.MapData{
	"username": []string{"required:You must provide username", "between:The username field must be between 3 to 8 chars"},
	"zip":      []string{"numeric:Please provide zip field as numeric"},
}

opts := govalidator.Options{
	Messages:        messages,
}

Contribution

If you are interested to make the package better please send pull requests or create an issue so that others can fix. Read the contribution guide here

Contributors

See all contributors

See benchmarks

Read API documentation

License

The govalidator is an open-source software licensed under the MIT License.