vd

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2026 License: BSD-3-Clause Imports: 7 Imported by: 0

Documentation

Overview

Package vd provides a configurable validator wrapper for go-playground/validator with Hertz framework integration and custom validation rules support.

Hertz Integration

Use with Hertz server by passing the validator engine to server options:

import (
    "github.com/cloudwego/hertz/pkg/app/server"
    "github.com/kainonly/go/vd"
)

func main() {
    // Create validator with default rules (snake, sort)
    v := vd.Default()

    // Or create with custom rules
    v := vd.New(
        vd.SetTag("vd"),  // optional, "vd" is default
        vd.SetRules(
            vd.Snake(),
            vd.Sort(),
            vd.Phone(),
            vd.IDCard(),
            vd.PasswordMedium(),
        ),
    )

    // Pass to Hertz server
    h := server.Default(
        server.WithHostPorts(":8080"),
        server.WithCustomValidator(v.Engine()),
    )

    h.POST("/user", func(ctx context.Context, c *app.RequestContext) {
        var req struct {
            Name  string `json:"name" vd:"required,snake"`
            Phone string `json:"phone" vd:"required,phone"`
        }
        if err := c.BindAndValidate(&req); err != nil {
            c.JSON(400, map[string]any{"error": err.Error()})
            return
        }
        c.JSON(200, map[string]any{"message": "ok"})
    })

    h.Spin()
}

Available Rule Groups

  • All(): All available rules
  • Common(): Commonly used rules (snake, sort, phone, idcard, username, slug, password_medium)
  • Chinese(): Chinese localization rules (phone, idcard, bankcard, license_plate, etc.)
  • NamingConvention(): Code naming rules (snake, pascal, camel, kebab, upper_snake, variable)

Custom Rules

Register custom validation rules:

v := vd.New(vd.SetRules(
    vd.Rule{
        Tag: "even",
        Fn: func(fl vd.FieldLevel) bool {
            return fl.Field().Int() % 2 == 0
        },
    },
))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FieldLevel

type FieldLevel = validator.FieldLevel

FieldLevel contains all the information and helper functions to validate a field.

type Option

type Option func(*options)

Option configures the Validator.

func SetRules

func SetRules(rules ...Rule) Option

SetRules sets the custom validation rules.

func SetTag

func SetTag(tag string) Option

SetTag sets the validation struct tag name. Default is "vd".

type Rule

type Rule struct {
	Tag  string
	Fn   ValidationFunc
	Call bool // CallValidationEvenIfNull
}

Rule defines a custom validation rule.

func All

func All() []Rule

All returns all available custom rules.

func AlphaNumDash

func AlphaNumDash() Rule

AlphaNumDash validates alphanumeric string with dashes and underscores. More permissive than alphanum, useful for slugs and identifiers. Example: "my-item_123"

func AlphaNumSpace

func AlphaNumSpace() Rule

AlphaNumSpace validates alphanumeric string with spaces. Example: "Hello World 123"

func BankCard

func BankCard() Rule

BankCard validates Chinese bank card number (16-19 digits with Luhn check). Example: "6222021234567890123"

func CamelCase

func CamelCase() Rule

CamelCase validates camelCase format. Example: "myVariable", "getUserName"

func Chinese

func Chinese() []Rule

Chinese returns all Chinese localization rules.

func ChineseName

func ChineseName() Rule

ChineseName validates Chinese person name (2-6 Chinese characters, may include ·). Example: "张三", "欧阳修", "古力娜扎·迪丽热巴"

func ChineseWord

func ChineseWord() Rule

ChineseWord validates that string contains only Chinese characters. Example: "中国", "你好世界"

func Color

func Color() Rule

Color validates color code (hex without # prefix). Note: validator has "hexcolor" with #, this is without. Example: "ff5733", "FFF", "abc123"

func Common

func Common() []Rule

Common returns commonly used rules (snake, sort, phone, idcard, username, slug, password_medium).

func Decimal

func Decimal() Rule

Decimal validates decimal number string with optional precision. Example: "123.45", "0.001"

func Domain

func Domain() Rule

Domain validates domain name without protocol. Note: validator has "fqdn" but this is simpler domain check. Example: "example.com", "sub.example.co.uk"

func FileExt

func FileExt() Rule

FileExt validates file extension (with or without dot). Example: ".pdf", "pdf", ".tar.gz"

func FileName

func FileName() Rule

FileName validates file name (no path separators). Example: "document.pdf", "image_01.png"

func FilePath

func FilePath() Rule

FilePath validates file path format (Unix or Windows style). Example: "/home/user/file.txt", "C:\Users\file.txt"

func IDCard

func IDCard() Rule

IDCard validates Chinese ID card number (18 digits). Example: "110101199003077758"

func KebabCase

func KebabCase() Rule

KebabCase validates kebab-case format. Example: "my-component", "user-profile-card"

func LicensePlate

func LicensePlate() Rule

LicensePlate validates Chinese vehicle license plate number. Supports regular plates and new energy vehicle plates. Example: "京A12345", "沪A12345D", "粤B123456"

func NamingConvention

func NamingConvention() []Rule

NamingConvention returns all naming convention rules.

func NotBlank

func NotBlank() Rule

NotBlank validates string is not empty and not only whitespace. Example: "hello" (valid), " " (invalid)

func ObjectID

func ObjectID() Rule

ObjectID validates MongoDB ObjectId (24 hex characters). Note: validator has "mongodb" for connection string, this is for ObjectId. Example: "507f1f77bcf86cd799439011"

func PascalCase

func PascalCase() Rule

PascalCase validates PascalCase format. Example: "MyClass", "UserService"

func PasswordMedium

func PasswordMedium() Rule

PasswordMedium validates medium strength password. At least 8 chars, must contain letters and numbers. Example: "password123"

func PasswordStrong

func PasswordStrong() Rule

PasswordStrong validates strong password. At least 8 chars, must contain uppercase, lowercase, number, and special char. Example: "Password123!"

func PasswordWeak

func PasswordWeak() Rule

PasswordWeak validates weak password (at least 6 chars). Example: "123456"

func Phone

func Phone() Rule

Phone validates Chinese mobile phone number format. Example: "13800138000"

func PositiveDecimal

func PositiveDecimal() Rule

PositiveDecimal validates positive decimal number string. Example: "123.45", "0.001"

func QQ

func QQ() Rule

QQ validates QQ number (5-11 digits, not starting with 0). Example: "12345", "1234567890"

func SafeString

func SafeString() Rule

SafeString validates string contains no dangerous characters for injection. Rejects: < > " ' ` ; & | $ \ and null bytes. Example: "safe text 123"

func Slug

func Slug() Rule

Slug validates URL slug format (lowercase, numbers, hyphens). Example: "my-blog-post", "article-123"

func Snake

func Snake() Rule

Snake validates snake_case format (lowercase letters and underscores only). Example: "user_name", "created_at"

func Snowflake

func Snowflake() Rule

Snowflake validates Snowflake ID (positive integer, typically 18-19 digits). Example: "1234567890123456789"

func Sort

func Sort() Rule

Sort validates sort format: "field_name:1" or "field_name:-1" Example: "created_at:1", "name:-1"

func TelPhone

func TelPhone() Rule

TelPhone validates telephone number (landline, Chinese format). Example: "010-12345678", "0755-1234567", "02112345678"

func USCC

func USCC() Rule

USCC validates Unified Social Credit Code (统一社会信用代码). 18-character code for Chinese organizations. Example: "91310000MA1FL8TQ32"

func UpperSnake

func UpperSnake() Rule

UpperSnake validates UPPER_SNAKE_CASE format. Example: "MAX_VALUE", "HTTP_STATUS_OK"

func Username

func Username() Rule

Username validates username format (alphanumeric, underscore, 3-20 chars). Example: "john_doe", "user123"

func Variable

func Variable() Rule

Variable validates variable name (programming convention). Starts with letter or underscore, alphanumeric and underscore only. Example: "myVar", "_private", "MAX_VALUE"

func Version

func Version() Rule

Version validates semantic version format. Note: validator has "semver" but this is a simpler version check. Example: "1.0.0", "2.1.3"

func WeChat

func WeChat() Rule

WeChat validates WeChat ID format. 6-20 chars, starts with letter, alphanumeric and underscore only. Example: "wxid_abc123", "myWeChat_01"

func ZipCode

func ZipCode() Rule

ZipCode validates Chinese postal code (6 digits). Example: "100000", "518000"

type ValidationFunc

type ValidationFunc = validator.Func

ValidationFunc is a custom validation function type.

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator wraps go-playground validator with custom configuration.

func Default

func Default() *Validator

Default creates a Validator with preset rules (snake, sort).

func New

func New(opts ...Option) *Validator

New creates a new Validator with the given options.

func (*Validator) Core

func (v *Validator) Core() *validator.Validate

Core returns the underlying go-playground/validator/v10 instance.

func (*Validator) Engine

func (v *Validator) Engine() *go_playground.Validator

Engine returns the underlying go-playground validator for Hertz.

func (*Validator) RegisterRule

func (v *Validator) RegisterRule(rule Rule) error

RegisterRule registers a custom validation rule dynamically.

func (*Validator) Validate

func (v *Validator) Validate(obj any) error

Validate validates a struct.

func (*Validator) ValidateVar

func (v *Validator) ValidateVar(field any, tag string) error

ValidateVar validates a single variable using tag style validation.

Jump to

Keyboard shortcuts

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