• Stars
    star
    1,273
  • Rank 35,451 (Top 0.8 %)
  • Language
    Go
  • License
    MIT License
  • Created over 6 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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

License

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

More Repositories

1

gojsonq

A simple Go package to Query over JSON/YAML/XML/CSV Data
Go
2,138
star
2

docgen

Transform your postman collection to HTML/Markdown documentation
Go
935
star
3

renderer

Simple, lightweight and faster response (JSON, JSONP, XML, YAML, HTML, File) rendering package for Go
Go
261
star
4

laravel-schema

Display the connected database information from Terminal.
PHP
111
star
5

task

Terminal tasks todo with reminder tool for geek
Go
81
star
6

retry

Simple and easy retry mechanism package for Go
Go
65
star
7

dl

Command-line file downloader tool
Go
47
star
8

ubuntu-live-wallpaper

Live wallpaper changer for ubuntu. Inspired from chrome momentum extension
Python
45
star
9

lumen-route-list

Display all the registered route list in lumen application just like laravel.
PHP
35
star
10

orchid-micro

Golang boilerplate using gin-gonic framework and gorm for microservice
Go
30
star
11

todoapp

Tutorial purpose repository
Go
27
star
12

docgen-bin

Transform your postman collection to html documentation
26
star
13

slack-notifier

This script will help you to send slack scheduled notification (message)
Python
22
star
14

world-countries

Provide world country list with country code, city, states and flag
PHP
19
star
15

gomailer

Gomailer provides a simple email interface to integrate third party email services.
Go
14
star
16

bongo

Terminal based bengali calendar
Go
14
star
17

ponjika

Tiny bengali ponjika based on Gregorian date
Go
12
star
18

orchid

A MVC style boilerplate for golang
Go
11
star
19

snapshot

Robust, Persistent, Key-Value (KV) store purely written in Golang
Go
11
star
20

traffic

Thread safe load-balancer package for Golang
Go
10
star
21

radar

Package radar help to debug nested function call and Trace current file/line
Go
9
star
22

unpack

Go assignment by slice, array unpacking or destructuring
Go
9
star
23

q

[WIP] "q" a command-line tool to query JSON/XML/YAML/CSV document
Go
8
star
24

iter

Iter provides functionality like Python's range function to iterate over numbers and letters
Go
8
star
25

querybuilder

A fake query builder to demonstrate the factory and singleton pattern
Go
7
star
26

multiple_route

MultipleRoute generator is helpful create any number of routes for your large laravel project.
PHP
6
star
27

clean

[WIP] Trying to make a boilerplate for clean-architecture in Golang
Go
5
star
28

task_binaries

Task binary files
5
star
29

timezones

PHP supported timezones array
PHP
4
star
30

dictionary

Offline terminal dictionary
Go
3
star
31

thedevsaddam.github.io

Personal blog site
CSS
3
star
32

dj1.9

learning django 1.9 with python 3
Python
3
star
33

vue1-learning

Playing with vue.js v1.0
HTML
3
star
34

thedevsaddam

Portfolio Page
3
star
35

enToBnDigit

English digit to bengali digit...
PHP
3
star
36

py-ghataghati

Just trying to figure out python
Python
3
star
37

py-app

Learning django
Python
3
star
38

go-repl

GO REPL is a simple application promising to write/compile/run code in terminal, inspired by python shell
Go
3
star
39

pc-ready

Its a shell script that will setup essential software and development environment for your Ubuntu OS
Shell
3
star
40

vue-simple-todo

Simple vue todo
HTML
3
star
41

go-ladder

Database migration package for golang inspired by Laravel migration
3
star
42

dj-project

Learning django...
Python
3
star
43

erlang

Playing with Erlang
Erlang
2
star
44

files

Contains files for public repositories
2
star
45

homebrew-cli

Contains formula for different tools for mac
Ruby
2
star
46

es6

ECMAScript 6, also known as ECMAScript 2015
JavaScript
2
star
47

worker

Go
2
star
48

go_repl_binaries

GO REPL is a simple application promising to write/compile/run code in terminal, inspired by python shell
2
star
49

ubuntu-500px-wallpaper

Inspired from chrome momentum extension. Get new wallpaper from 500px popular section, each time restart the computer.
Shell
2
star
50

30-seconds-of-go

2
star
51

reactjs

Learning react js
JavaScript
2
star
52

tweet-release

Go
1
star
53

action

GitHub action to supercharge your pull requests workflows!
Go
1
star
54

assessment-200

Python
1
star
55

lo_

A modern Rust utility library delivering modularity, performance & extras proted from JavaScript Lodash
Rust
1
star