Skip to main content

Validator

Ryan SUAbout 4 min

Validator Tutorial

Video tutorial

Simple Admin Tools integration validatoropen in new window library

You can just edit api file and add validate tag for the struct.

 // login request | 登录参数
    // swagger:model LoginReq
    LoginReq {
        // User Name | 用户名
        Username   string `json:"username" validate:"alphanum,max=20"`

        // Password | 密码
        Password   string `json:"password" validate:"max=30,min=6"`

        // Captcha ID which store in redis | 验证码编号, 存在redis中
        CaptchaID  string `json:"captchaId"  validate:"len=20"`

        // The Captcha which users input | 用户输入的验证码
        Captcha    string `json:"captcha" validate:"len=5"`
    }

Extend interface

The following three interfaces are provided for extending the validator, which only need to be called in the main function

// Register additional languages
httpx.RegisterValidationTranslation(tag string, trans ut.Translator, registerFn validator.RegisterTranslationsFunc,
translationFn validator. TranslationFunc)

// register custom method
httpx.RegisterValidation(tag string, fn validator.Func)

// Set a custom error code
httpx.SetValidatorErrorCode(code int)

Example

package main

import (
	"flag"
	"fmt"

	"github.com/zeromicro/go-zero/rest/httpx"

	"github.com/suyuan32/simple-admin-core/api/internal/config"
	"github.com/suyuan32/simple-admin-core/api/internal/handler"
	"github.com/suyuan32/simple-admin-core/api/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/core.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c, conf.UseEnv())

	server := rest.MustNewServer(c.RestConf, rest.WithCors("*"))
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

    // Set custom error code for validator
	httpx.SetValidatorErrorCode(5000)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}

Notice: validate tag dose not allow empty by default,if you allow empty, you should add omitempty

// Get token list request params | token列表请求参数
    // swagger:model TokenListReq
    TokenListReq {
        PageInfo
        // User's UUID | 用户的UUID
        // Required: true
        // Max Length: 36
        UUID      string `json:"UUID" validate:"omitempty,len=36"`

        // user's nickname | 用户的昵称
        // Required: true
        // Max length: 10
        Nickname  string  `json:"nickname" validate:"omitempty,alphanumunicode,max=10"`

        // User Name | 用户名
        // Required: true
        // Max length: 20
        Username   string `json:"username" validate:"omitempty,alphanum,max=20"`

        // The user's email address | 用户的邮箱
        // Required: true
        // Max length: 100
        Email     string `json:"email" validate:"omitempty,email,max=100"`
    }

Validation is automatically generated

Warning

After goctls v0.3.1, validate full-end automatic generation is supported, just declare validate tag in the api file

For the string type, support max, min, len, required checks are automatically generated to swagger, backend For int - float types, support lt,lte,gt,gte, required checksums are automatically generated to swagger, backend

Cancel validating

If you do not want to use validator, set isValidate in Parse to false in Handler

if err := httpx. Parse(r, &req, false); err != nil {
     httpx.ErrorCtx(r.Context(), w, err)
     return
}

Support Types

Fields

TagDescription
eqcsfieldField Equals Another Field (relative)
eqfieldField Equals Another Field
fieldcontainsNOT DOCUMENTED IN doc.go
fieldexcludesNOT DOCUMENTED IN doc.go
gtcsfieldField Greater Than Another Relative Field
gtecsfieldField Greater Than or Equal To Another Relative Field
gtefieldField Greater Than or Equal To Another Field
gtfieldField Greater Than Another Field
ltcsfieldLess Than Another Relative Field
ltecsfieldLess Than or Equal To Another Relative Field
ltefieldLess Than or Equal To Another Field
ltfieldLess Than Another Field
necsfieldField Does Not Equal Another Field (relative)
nefieldField Does Not Equal Another Field

Network

TagDescription
cidrClassless Inter-Domain Routing CIDR
cidrv4Classless Inter-Domain Routing CIDRv4
cidrv6Classless Inter-Domain Routing CIDRv6
datauriData URL
fqdnFull Qualified Domain Name (FQDN)
hostnameHostname RFC 952
hostname_portHostPort
hostname_rfc1123Hostname RFC 1123
ipInternet Protocol Address IP
ip4_addrInternet Protocol Address IPv4
ip6_addrInternet Protocol Address IPv6
ip_addrInternet Protocol Address IP
ipv4Internet Protocol Address IPv4
ipv6Internet Protocol Address IPv6
macMedia Access Control Address MAC
tcp4_addrTransmission Control Protocol Address TCPv4
tcp6_addrTransmission Control Protocol Address TCPv6
tcp_addrTransmission Control Protocol Address TCP
udp4_addrUser Datagram Protocol Address UDPv4
udp6_addrUser Datagram Protocol Address UDPv6
udp_addrUser Datagram Protocol Address UDP
unix_addrUnix domain socket end point Address
uriURI String
urlURL String
url_encodedURL Encoded
urn_rfc2141Urn RFC 2141 String

Strings

TagDescription
alphaAlpha Only
alphanumAlphanumeric
alphanumunicodeAlphanumeric Unicode
alphaunicodeAlpha Unicode
asciiASCII
booleanBoolean
containsContains
containsanyContains Any
containsruneContains Rune
endsnotwithEnds Not With
endswithEnds With
excludesExcludes
excludesallExcludes All
excludesruneExcludes Rune
lowercaseLowercase
multibyteMulti-Byte Characters
numberNOT DOCUMENTED IN doc.go
numericNumeric
printasciiPrintable ASCII
startsnotwithStarts Not With
startswithStarts With
uppercaseUppercase

Format

TagDescription
base64Base64 String
base64urlBase64URL String
bicBusiness Identifier Code (ISO 9362)
bcp47_language_tagLanguage tag (BCP 47)
btc_addrBitcoin Address
btc_addr_bech32Bitcoin Bech32 Address (segwit)
credit_cardCredit Card Number
datetimeDatetime
e164e164 formatted phone number
emailE-mail String
eth_addrEthereum Address
hexadecimalHexadecimal String
hexcolorHexcolor String
hslHSL String
hslaHSLA String
htmlHTML Tags
html_encodedHTML Encoded
isbnInternational Standard Book Number
isbn10International Standard Book Number 10
isbn13International Standard Book Number 13
iso3166_1_alpha2Two-letter country code (ISO 3166-1 alpha-2)
iso3166_1_alpha3Three-letter country code (ISO 3166-1 alpha-3)
iso3166_1_alpha_numericNumeric country code (ISO 3166-1 numeric)
iso3166_2Country subdivision code (ISO 3166-2)
iso4217Currency code (ISO 4217)
jsonJSON
jwtJSON Web Token (JWT)
latitudeLatitude
longitudeLongitude
postcode_iso3166_alpha2Postcode
postcode_iso3166_alpha2_fieldPostcode
rgbRGB String
rgbaRGBA String
ssnSocial Security Number SSN
timezoneTimezone
uuidUniversally Unique Identifier UUID
uuid3Universally Unique Identifier UUID v3
uuid3_rfc4122Universally Unique Identifier UUID v3 RFC4122
uuid4Universally Unique Identifier UUID v4
uuid4_rfc4122Universally Unique Identifier UUID v4 RFC4122
uuid5Universally Unique Identifier UUID v5
uuid5_rfc4122Universally Unique Identifier UUID v5 RFC4122
uuid_rfc4122Universally Unique Identifier UUID RFC4122
md4MD4 hash
md5MD5 hash
sha256SHA256 hash
sha384SHA384 hash
sha512SHA512 hash
ripemd128RIPEMD-128 hash
ripemd128RIPEMD-160 hash
tiger128TIGER128 hash
tiger160TIGER160 hash
tiger192TIGER192 hash
semverSemantic Versioning 2.0.0
ulidUniversally Unique Lexicographically Sortable Identifier ULID

Comparisons

TagDescription
eqEquals
gtGreater than
gteGreater than or equal
ltLess Than
lteLess Than or Equal
neNot Equal

Other

TagDescription
dirDirectory
fileFile path
isdefaultIs Default
lenLength
maxMaximum
minMinimum
oneofOne Of
requiredRequired
required_ifRequired If
required_unlessRequired Unless
required_withRequired With
required_with_allRequired With All
required_withoutRequired Without
required_without_allRequired Without All
excluded_ifExcluded If
excluded_unlessExcluded Unless
excluded_withExcluded With
excluded_with_allExcluded With All
excluded_withoutExcluded Without
excluded_without_allExcluded Without All
uniqueUnique

Aliases

TagDescription
iscolorhexcolor|rgb|rgba|hsl|hsla
country_codeiso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric