小孩子手足口病有什么症状图片| 庚寅五行属什么| 脑萎缩吃什么药| 电脑一体机什么牌子好| 鼻孔流血是什么原因| 什么是气质| 真好是什么意思| 告诫是什么意思| 孕妇梦见狗是什么意思| 肠胃炎喝什么药| 妊娠试验阴性是什么意思| 2023什么年| 1226是什么星座| 停车坐爱枫林晚的坐是什么意思| 什么是18k金| 中国国酒是什么酒| 体现是什么意思| 什么字最难写| 总手是什么意思| 县纪委副书记什么级别| 藏红花泡水喝有什么功效| 怀孕不能吃什么水果| 神经性头疼吃什么药效果好| 牙掉了是什么预兆| 左心室高电压是什么意思| 11.16是什么星座| 血管堵塞吃什么好| 儿童头痛挂什么科| bodywash是什么意思| 脸上长斑是因为什么原因引起的| 什么是老赖| 什么药降肌酐| 欣什么若什么| 为什么猫怕水| 高血糖可以吃什么水果| 胃肠炎吃什么药好| 盆腔炎是什么| 冻顶乌龙茶是什么茶| 白露是什么时候| 扁平疣用什么药膏除根| 高代表什么生肖| 消化内科是看什么病的| 肺炎后遗症有什么症状| 血糖高吃什么药最好| 梦见很多棺材是什么征兆| 子母门是什么意思| 破伤风有什么作用| 胆囊炎吃什么药效果最好| cooh是什么基| 珍珠五行属什么| 花漾是什么意思| 姓薄的读音是什么| 阴囊瘙痒用什么药| 什么茶不能喝| 明朝北京叫什么| 梦见自己请客吃饭是什么意思| 嗜碱性粒细胞偏高是什么原因| 火花塞坏了有什么症状| 肚子胀气吃什么食物| tissot是什么牌子1853| 玉对人体有什么好处| 白内障是什么原因引起的| 岫岩玉是什么玉| 叉烧是什么肉做的| 福相是什么意思| 双肺索条灶是什么意思| 左下腹疼痛是什么原因女性| 喉炎是什么原因引起的| 摊手是什么意思| 神经病吃什么药效果好| 什么叫肺间质病变| 知音是什么意思| 吃饭出汗多是什么原因| 9月30日什么星座| 吃梨有什么好处| 什么药不能一起吃| b是什么单位| 双侧骶髂关节致密性骨炎是什么病| 链球菌感染是什么病| 为什么会有盆腔炎| 3月27日是什么星座| 多种维生素什么牌子的效果最好| 眼睛屈光不正是什么意思| 1999是什么年| 宝宝贫血有什么危害| 夏天适合喝什么茶| 贞洁是什么意思| 什么是腺样体肥大| 宫颈lsil是什么意思| 男人很man是什么意思| 救人一命胜造七级浮屠是什么意思| 食管炎有什么症状| ace是什么| 儿童腮腺炎挂什么科| 32周岁属什么生肖| 特朗普为什么叫川普| 僧侣是什么意思| 瑶五行属性是什么| 感冒发烧吃什么饭菜好| 口腔溃疡为什么是白色的| 吐司是什么| 什么叫边界感| 微光是什么意思| 天秤女喜欢什么样的男生| 一天两包烟会导致什么后果| 精液是什么味道| 洗耳朵用什么药水| 脑震荡挂什么科| 怀孕吃什么菜最有营养| 治疗宫颈炎用什么药好得快| 鸡肉和什么菜搭配最好| 心悸心慌吃什么药| 乙肝抗体阴性什么意思| 05年属鸡的是什么命| 象牙带身上有什么好处| 什么时候看到的月亮最大| 柚子是什么季节的水果| 区局长是什么级别| 大惊小怪是什么生肖| 无致病菌生长是什么意思| 物以类聚人以群分什么意思| 蓝光是什么| 谁也不知道下一秒会发生什么| 蓝莓对身体有什么好处| 井柏然原名叫什么| eagle是什么意思| 皮肤上出现小红点是什么原因| 不亚于是什么意思| 孕妇梦见蛇是什么意思| 肠子有问题有什么症状| 沉淀是什么意思| 境遇是什么意思| 搏击是什么运动| 尿酸高适合喝什么汤| 胃难受吃什么食物好| 种植牙有什么风险和后遗症| 胸闷挂什么科室| 梦到屎是什么意思| 蒲公英什么时候播种| 甲状腺在人体什么位置| 肛门疼痛是什么原因| 长期吃二甲双胍有什么副作用| 大健康是什么意思| 容易脸红的人是什么原因| 女性漏尿挂什么科| 嗜碱性粒细胞比率偏高说明什么| 死于非命是什么意思| 画蛇添足的故事告诉我们什么道理| 85年是什么命| 牙疼买什么药| 处女女和什么星座最配| 龟头炎挂什么科| 蛇属于什么动物| 明矾有什么作用| 年轻人白头发是什么原因引起的| 乖乖是什么意思| 手术后吃什么营养品好| 吃什么睡眠好的最快最有效| 流口水什么原因| 什么东西有脚却不能走路| 美国有什么特产| 慢性荨麻疹是什么原因引起的| 鹿加几念什么| 2007年属猪五行属什么| 宫腔内偏强回声是什么意思| 波推飞机什么意思| 梦见照相是什么意思| 18岁属什么生肖| 不全骨折是什么意思| 眼睛视物模糊是什么原因| 7月份什么星座| 乙肝表面抗原携带者什么意思| 黑色搭配什么颜色好看| 去医院测血糖挂什么科| 吃什么去肝火效果最好| 什么是便血| 白目是什么意思| 佐助是什么意思| 向日葵是什么季节| 全身燥热是什么原因引起的| 痔疮的症状是什么| 血小板低吃什么| 霉菌性阴道炎是什么症状| 一月23号是什么星座| 午睡睡不着是什么原因| 五音指什么| 孩子晚上睡觉磨牙是什么原因| 血管堵塞用什么药| 牙龈疼吃什么消炎药| 做梦梦见别人怀孕是什么意思| 舌头白色的是什么原因| 什么是回避型依恋人格| 什么中不足成语| 什么什么生机| 小孩尿味道很重是什么原因| 判处死刑缓期二年执行是什么意思| mu是什么意思| 皮肤湿疹用什么药膏| g是什么牌子| 什么旺水命| 入围是什么意思| 替身是什么意思| 息肉和痔疮有什么区别| 大美是什么意思| 乘晕宁又叫什么| 喝茶叶有什么好处| 鲅鱼是什么鱼| 女生胸痛什么原因| 三冬是什么意思| 鱿鱼属于什么类| 产值是什么| 原生家庭什么意思| 囊肿是什么意思| 湿疹和热疹有什么区别| 血小板是什么颜色的| 身份证后面有个x是什么意思| 布洛芬什么时候吃| 什么洗发水去屑好| 白塞氏病是什么病| 蝉属于什么类动物| 三星堆为什么叫三星堆| ich是什么意思| 同一首歌为什么停播了| 梦见抓鸟是什么征兆| 盐为什么要加碘| 中秋节吃什么| 6月6日什么星座| 腿容易麻是什么原因| 玉米须煮水喝有什么好处| 脊髓炎吃什么药| 胃肠功能紊乱是什么意思| 胸部疼痛挂什么科| mchc偏低是什么意思| 国画是什么| 什么品种的狗最粘人| 雪莲果什么季节成熟| 偏头痛吃什么药效果好| 什么叫心律不齐| 2004是什么年| 为什么总是耳鸣| 肺积水是什么原因引起的| 中性粒细胞偏低是什么意思| 长方形纸能折什么| 斐乐手表属于什么档次| 脚趾头麻木是什么原因引起的| 青蛙趴有什么好处| 怀孕了吃什么| 石英机芯什么意思| 荆轲姓什么| 眼睛为什么会肿| 肉炒什么好吃| 为什么说啄木鸟是树的医生| 1月1日什么星座| 输卵管堵塞什么症状| 什么是玄关| 完全性右束支阻滞是什么意思| 大便次数多什么原因| cd是什么意思| 斜杠青年什么意思| 1月27日是什么星座| 什么情况需要做胃镜| peppa是什么意思| 泪河高度说明什么| 唐僧是什么佛| 百度
Skip to content

thedevsaddam/govalidator

Repository files navigation

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.

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

晚上11点到12点是什么时辰 娘家人是什么意思 孕妇梦见鬼是什么预兆 uno是什么 reed是什么意思
老人头发由白变黑是什么原因 眼睛感染用什么眼药水 深圳少年宫有什么好玩的 hiv阴性是什么意思 凌晨3点多是什么时辰
头皮痒是什么原因引起的 摩羯座女和什么星座最配 尿血应该挂什么科 秒杀是什么意思 眼圈发黑什么原因
ab和a型血生的孩子是什么血型 人的牙齿为什么不能再生 2013年是什么命 中水是什么水 pca是什么意思
吃了螃蟹不能吃什么helloaicloud.com 4s店是什么意思baiqunet.com 双花红棍什么意思hcv7jop6ns0r.cn 看到刺猬有什么预兆cj623037.com 为什么会甲亢hcv8jop2ns7r.cn
喉咙痛吃什么水果好hcv9jop7ns1r.cn 温煦是什么意思hcv9jop4ns5r.cn 10月30号什么星座jasonfriends.com 无名指和食指一样长代表什么520myf.com g1p1是什么意思hcv8jop1ns7r.cn
梦见买鸡蛋是什么意思周公解梦hcv8jop4ns9r.cn 喉咙有异物感是什么原因hcv9jop5ns8r.cn 三维是什么hcv8jop6ns3r.cn 蓝矾对人有什么危害hcv8jop5ns0r.cn 泌尿科属于什么科hcv9jop4ns1r.cn
黑洞里面是什么fenrenren.com 什么东西最刮油减肥hcv9jop0ns5r.cn 什么花园jasonfriends.com 慢性阑尾炎挂什么科hcv8jop0ns1r.cn 海王星是什么颜色hcv8jop2ns7r.cn
百度