validate

package module
v0.0.0-...-e6bece3 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2024 License: MIT Imports: 10 Imported by: 0

README

Validate

验证结构体的属性或方法,只需在需要验证的属性或方法后面添加validate标签即可。例如:

type User struct {
    ID uint `validate:"required;length=9"`
    Username string `validate:"required;length=[5, 10]"`
    Password string `validate:"required;password=h"`
    Nickname string
    Age uint `validate:"range=[15,]"`
    Sex string `validate:"enum=(男,女)"`
    RegTime string `validate:"datetime"`
    Email string `validate:"email;required='IsAdmin'==true"`
    IsAdmin bool
}

释义:

ID 必填;长度为9

Username 必填;长度最短为5,最长为10

Password 必填;密码复杂度为高

Age 最小值为15

Sex 只能是男,女的其中一个

RegTime 值是日期时间格式

Email 值是邮件格式;当属性IsaAdmintrue时,该属性为必填

validate支持以下验证:

字段名 描述 示例
required 布尔值或布尔表达式 是否必填,如果有required但没有指定值,默认为true validate:"required"
email 电子邮件格式 validate:"email"
datetime 日期时间格式 validate:"datetime"
date 日期格式 validate:"date"
phone 国际区号 合法电话号码,国际区号默认是+86 validate:"phone"
validate:"phone=+852"
length uint或区间表达式 长度或最大长度、最小长度,可以只限制最小或最大
仅适用于len()能计算的类型
validate:"length=15"
validate:"length=[5,15]"
enum (值1,值2,...) 只能是枚举的值 validate:"enum=(男,女)"
password `h m l`
url URL格式的字符串 validate:"url"
range 区间表达式 取值范围,可以只限制最小或最大;数值类 validate:"range=[3.24, 8.74]"
prefix string 规定字符串以什么开始 validate:"prefix=/"
suffix string 规定字符串以什么结束 validate:"suffix=."

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsDate

func IsDate(str string) bool

是否日期格式

func IsDatetime

func IsDatetime(str string) bool

是否日期时间格式

func IsMail

func IsMail(str string) bool

是否是邮件格式

func IsPhone

func IsPhone(phone string) bool

是否是正确的电话号码

func IsURL

func IsURL(u string) bool

是否是URL

func Struct

func Struct(data interface{}) (bool, error)

对结构体的属性或方法进行验证

data可以是结构体、结构体切片、结构体映射、结构体指针

true 验证通过

false 验证失败

Types

This section is empty.

Jump to

Keyboard shortcuts

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