govalidator

package module
v1.9.10 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2020 License: MIT Imports: 14 Imported by: 194

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.

Documentation

Index

Constants

View Source
const (
	// Alpha represents regular expression for alpha characters
	Alpha string = "^[a-zA-Z]+$"
	// AlphaDash represents regular expression for alpha characters with underscore and dash
	AlphaDash string = "^[a-zA-Z0-9_-]+$"
	// AlphaSpace represents regular expression for alpha characters with underscore, space and dash
	AlphaSpace string = "^[-a-zA-Z0-9_ ]+$"
	// AlphaNumeric represents regular expression for alpha numeric characters
	AlphaNumeric string = "^[a-zA-Z0-9]+$"
	// CreditCard represents regular expression for credit cards like (Visa, MasterCard, American Express, Diners Club, Discover, and JCB cards). Ref: https://stackoverflow.com/questions/9315647/regex-credit-card-number-tests
	CreditCard string = "" /* 154-byte string literal not displayed */
	// Coordinate represents latitude and longitude regular expression
	Coordinate string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?),\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" // Ref: https://stackoverflow.com/questions/3518504/regular-expression-for-matching-latitude-longitude-coordinates
	// CSSColor represents css valid color code with hex, rgb, rgba, hsl, hsla etc. Ref: http://www.regexpal.com/97509
	CSSColor string = "^(#([\\da-f]{3}){1,2}|(rgb|hsl)a\\((\\d{1,3}%?,\\s?){3}(1|0?\\.\\d+)\\)|(rgb|hsl)\\(\\d{1,3}%?(,\\s?\\d{1,3}%?){2}\\))$"
	// Date represents regular expression for valid date like: yyyy-mm-dd
	Date string = "" /* 231-byte string literal not displayed */
	// DateDDMMYY represents regular expression for valid date of format dd/mm/yyyy , dd-mm-yyyy etc.Ref: http://regexr.com/346hf
	DateDDMMYY string = "^(0?[1-9]|[12][0-9]|3[01])[\\/\\-](0?[1-9]|1[012])[\\/\\-]\\d{4}$"
	// Digits represents regular epxression for validating digits
	Digits string = "^[+-]?([0-9]*\\.?[0-9]+|[0-9]+\\.?[0-9]*)([eE][+-]?[0-9]+)?$"
	// Email represents regular expression for email
	Email string = "" /* 133-byte string literal not displayed */
	// Float represents regular expression for finding float number
	Float string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"
	// IP represents regular expression for ip address
	IP string = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
	// IPV4 represents regular expression for ip address version 4
	IPV4 string = "^([0-9]{1,3}\\.){3}[0-9]{1,3}(\\/([0-9]|[1-2][0-9]|3[0-2]))?$"
	// IPV6 represents regular expression for ip address version 6
	IPV6 string = `` /* 1057-byte string literal not displayed */
	// Latitude represents latitude regular expression
	Latitude string = "^(\\+|-)?(?:90(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\\.[0-9]{1,6})?))$"
	// Longitude represents longitude regular expression
	Longitude string = "^(\\+|-)?(?:180(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\\.[0-9]{1,6})?))$"
	// MacAddress represents regular expression for mac address
	MacAddress string = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"
	// Numeric represents regular expression for numeric
	Numeric string = "^-?[0-9]+$"
	// URL represents regular expression for url
	URL string = "^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$" // Ref: https://stackoverflow.com/questions/136505/searching-for-uuids-in-text-with-regex
	// UUID represents regular expression for UUID
	UUID string = "^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$"
	// UUID3 represents regular expression for UUID version 3
	UUID3 string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
	// UUID4 represents regular expression for UUID version 4
	UUID4 string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
	// UUID5 represents regular expression for UUID version 5
	UUID5 string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
)

Variables

This section is empty.

Functions

func AddCustomRule

func AddCustomRule(name string, fn func(field string, rule string, message string, value interface{}) error)

AddCustomRule help to add custom rules for validator First argument it takes the rule name and second arg a func Second arg must have this signature below fn func(name string, fn func(field string, rule string, message string, value interface{}) error see example in readme: https://github.com/thedevsaddam/govalidator#add-custom-rules

Types

type Bool

type Bool struct {
	Value bool `json:"value"`
	IsSet bool `json:"isSet"`
}

Bool describes a custom type of built-in bool data type

func (*Bool) MarshalJSON

func (i *Bool) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (*Bool) UnmarshalJSON

func (i *Bool) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type Float32

type Float32 struct {
	Value float32 `json:"value"`
	IsSet bool    `json:"isSet"`
}

Float32 describes a custom type of built-in float32 data type

func (*Float32) MarshalJSON

func (i *Float32) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (*Float32) UnmarshalJSON

func (i *Float32) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type Float64

type Float64 struct {
	Value float64 `json:"value"`
	IsSet bool    `json:"isSet"`
}

Float64 describes a custom type of built-in float64 data type

func (*Float64) MarshalJSON

func (i *Float64) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (*Float64) UnmarshalJSON

func (i *Float64) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type Int

type Int struct {
	Value int  `json:"value"`
	IsSet bool `json:"isSet"`
}

Int describes a custom type of built-in int data type

func (*Int) MarshalJSON

func (i *Int) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (*Int) UnmarshalJSON

func (i *Int) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type Int64

type Int64 struct {
	Value int64 `json:"value"`
	IsSet bool  `json:"isSet"`
}

Int64 describes a custom type of built-in int64 data type

func (*Int64) MarshalJSON

func (i *Int64) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (*Int64) UnmarshalJSON

func (i *Int64) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type MapData

type MapData map[string][]string

MapData represents basic data structure for govalidator Rules and Messages

type Options

type Options struct {
	Data            interface{} // Data represents structure for JSON body
	Request         *http.Request
	RequiredDefault bool    // RequiredDefault represents if all the fields are by default required or not
	Rules           MapData // Rules represents rules for form-data/x-url-encoded/query params data
	Messages        MapData // Messages represents custom/localize message for rules
	TagIdentifier   string  // TagIdentifier represents struct tag identifier, e.g: json or validate etc
	FormSize        int64   //Form represents the multipart forom data max memory size in bytes
}

Options describes configuration option for validator

type Validator

type Validator struct {
	Opts Options // Opts contains all the options for validator
}

Validator represents a validator with options

func New

func New(opts Options) *Validator

New return a new validator object using provided options

func (*Validator) SetDefaultRequired

func (v *Validator) SetDefaultRequired(required bool)

SetDefaultRequired change the required behavior of fields Default value if false If SetDefaultRequired set to true then it will mark all the field in the rules list as required

func (*Validator) SetTagIdentifier

func (v *Validator) SetTagIdentifier(identifier string)

SetTagIdentifier change the default tag identifier (json) to your custom tag.

func (*Validator) Validate

func (v *Validator) Validate() url.Values

Validate validate request data like form-data, x-www-form-urlencoded and query params see example in README.md file ref: https://github.com/thedevsaddam/govalidator#example

func (*Validator) ValidateJSON

func (v *Validator) ValidateJSON() url.Values

ValidateJSON validate request data from JSON body to Go struct see example in README.md file

func (*Validator) ValidateStruct added in v1.9.6

func (v *Validator) ValidateStruct() url.Values

Jump to

Keyboard shortcuts

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