valid

package module
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: May 1, 2024 License: MIT Imports: 16 Imported by: 0

README

pkg.go.dev

valid

The package valid defines a number of validation functions and other objects that can be used, together with the cmd/validgen tool, to generate struct field validation.

Most of validation logic in the ./valid.go file, including the related tests and comments, was ported over from https://github.com/validatorjs/validator.js


Table of Contents

  • An Example
  • Configuration
  • Rules
  • TODO adding custom validation functions
  • TODO configuring custom validation functions from file
  • TODO configuring custom validation functions using comments
  • TODO specifying arguments for validation functions
  • TODO passing dependencies to validation functions
  • TODO error handling
  • TODO default error handling
  • TODO custom error handling

An Introductory Example

Input
type UserCreateParams struct {
	FName string `is:"len:1:300" pre:"trim"`
	LName string `is:"len:1:300,required" pre:"trim"`
	Email string `is:"email,required" pre:"lower,trim"`
	Passw string `is:"strongpass,required" pre:"trim"`
	Age   int    `is:"min:3,max:150"`
}

type UserCreateParamsValidator struct {
	UserCreateParams
}
Generated Output
func (v UserCreateParamsValidator) Validate() error {
	v.FName = strings.TrimSpace(v.FName)
	if len(v.FName) < 1 || len(v.FName) > 300 {
		return errors.New("FName must be of length between: 1 and 300 (inclusive)")
	}
	v.LName = strings.TrimSpace(v.LName)
	if v.LName == "" {
		return errors.New("LName is required")
	} else if len(v.LName) < 1 || len(v.LName) > 300 {
		return errors.New("LName must be of length between: 1 and 300 (inclusive)")
	}
	v.Email = strings.TrimSpace(strings.ToLower(v.Email))
	if v.Email == "" {
		return errors.New("Email is required")
	} else if !valid.Email(v.Email) {
		return errors.New("Email must be a valid email address")
	}
	v.Passw = strings.TrimSpace(v.Passw)
	if v.Passw == "" {
		return errors.New("Passw is required")
	} else if !valid.StrongPassword(v.Passw, nil) {
		return errors.New("Passw must be a strong password")
	}
	if v.Age < 3 {
		return errors.New("Age must be greater than or equal to: 3")
	} else if v.Age > 150 {
		return errors.New("Age must be less than or equal to: 150")
	}
	return nil
}

Configuration

The validgen tool can be configured in two ways. Either by using CLI arguments (this is a limited approach), or with a YAML config file (this is the recommended and complete approach). To see the documentation for the CLI arguments, you can run:

validgen --help

To configure the tool using a specific file you can provide the -c file argument, e.g.

validgen -c /path/to/config.yaml

When the -c file argument is omitted, the tool will look in the nearest git-root directory of the current working directory for a file named .valid.yaml. If such a file is found the tool will use that to configure itself. The complete documentation of the config yaml file can be found here.

Rules

The validgen tool looks for particular struct tags that are then used as the instructions for what code the tool should generate. These instructions are referred to as rules and there are two distinct kinds:

  • validation rules (denoted with is:"..." structs tags) are used to generate struct field validation.
  • preprocessor rules (denoted with pre:"..." struct tags) are used to generate struct field "pre-processing".

Based on how these rules are implmenetated, they can be classified into the following categories:

  1. "builtin" validation rules: These rules are implemented using the Go langauge's primitive operators and builtin functionality. For a full list (with examples) of the builtin validation rules, see: builtin validation rules.
  2. "stdlib" validation rules: These rules are implemented using functions of the Go standard library. For a full list (with examples) of the stdlib validation rules, see: stdlib validation rules.
  3. "included" validation rules: These rules are implemented using functions from the github.com/frk/valid package. For a full list (with examples) of the included validation rules, see: included validation rules.
  4. "custom" validation rules: These rules are implemented with functions that are sourced from the configuration file's "rules" entry.
  5. "stdlib" preprocessor rules: These rules are implemented using functions of the Go standard library. For a full list (with examples) of available included validation rules, see: stdlib preprocessor rules.
  6. "custom" preprocessor rules: These rules are implemented with functions that are sourced from the configuration file's "rules" entry.
CUSTOM RULES

To be able to generate code that uses custom functions for validation and preprocessing you first need to declare and configure custom validation and preprocessor rules in the tool's yaml config file. The custom rules need to be declared in the config's "rules" entry. For details on how to configure custom rules, please read the documentation on rule_config and config.RuleConfig.

RULE SYNTAX

Following is a description of the rule syntax using EBNF:

node      = rule | [ "[" [ node ] "]" ] [ ( node | rule "," node ) ] .
rule      = rule_name [ { ":" rule_arg } ] { "," rule } .
rule_name = identifier .
rule_arg  = | boolean_lit | integer_lit | float_lit | string_lit | quoted_string_lit | field_reference .

boolean_lit       = "true" | "false" .
integer_lit       = "0" | [ "-" ] "1"…"9" { "0"…"9" } .
float_lit         = [ "-" ] ( "0" | "1"…"9" { "0"…"9" } ) "." "0"…"9" { "0"…"9" } .
string_lit        = .
quoted_string_lit = `"` `"` .

field_reference = field_ref_abs | field_ref_rel
field_ref_abs   = "&" field_key .
field_ref_rel   = "." field_key .
field_key       = identifier { field_key_separator identifier } .
field_key_sep   = "." | (* optionally specified by the user *)

identifier = letter { letter } .
letter     = "A"…"Z" | "a"…"z" | "_" .

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CurrencyOptsDefault = CurrencyOpts{
	NeedSym: false,
}
View Source
var StrongPasswordOptsDefault = StrongPasswordOpts{
	MinLen:     8,
	MinLower:   1,
	MinUpper:   1,
	MinNumbers: 1,
	MinSymbols: 1,
}

Functions

func ASCII

func ASCII(v string) bool

ASCII reports whether or not v is an ASCII string.

valid:rule.yaml

name: ascii
error: { text: "must contain only ASCII characters" }

func Alnum

func Alnum(v string, lang string) bool

Alnum reports whether or not v is a valid alphanumeric string.

valid:rule.yaml

name: alnum
args: [{ default: en }]
error: { text: "must be an alphanumeric string" }

func Alpha

func Alpha(v string, lang string) bool

Alpha reports whether or not v is a valid alphabetic string.

valid:rule.yaml

name: alpha
args: [{ default: en }]
error: { text: "must be an alphabetic string" }

func BIC

func BIC(v string) bool

BIC reports whether or not v represents a valid Bank Identification Code or SWIFT code.

valid:rule.yaml

name: bic
error: { text: "must be a valid BIC or SWIFT code" }

func BTC

func BTC(v string) bool

BTC reports whether or not v represents a valid BTC address.

valid:rule.yaml

name: btc
error: { text: "must be a valid BTC address" }

func Base32

func Base32(v string) bool

Base32 reports whether or not v is a valid base32 string.

valid:rule.yaml

name: base32
error: { text: "must be a valid base32 string" }

func Base58

func Base58(v string) bool

Base58 reports whether or not v is a valid base58 string.

valid:rule.yaml

name: base58
error: { text: "must be a valid base58 string" }

func Base64

func Base64(v string, urlsafe bool) bool

Base64 reports whether or not v is a valid base64 string.

NOTE: The standard "encoding/base64" package is used for validation. With urlsafe=false StdEncoding is used and with urlsafe=true RawURLEncoding is used.

valid:rule.yaml

name: base64
args:
  - default: false
    options: [{ value: true, alias: url }]
error: { text: "must be a valid base64 string" }

func Binary

func Binary(v string) bool

Binary reports whether or not v represents a valid binary integer.

valid:rule.yaml

name: binary
error: { text: "string content must match a binary number" }

func Bool

func Bool(v string) bool

Bool reports whether or not v represents a valid boolean. The following are considered valid boolean values: "true", "false", "TRUE", and "FALSE".

valid:rule.yaml

name: bool
error: { text: "string content must match a boolean value" }

func CIDR

func CIDR(v string) bool

CIDR reports whether or not v is a valid Classless Inter-Domain Routing notation.

NOTE: CIDR uses "net".ParseCIDR to determine the validity of v.

valid:rule.yaml

name: cidr
error: { text: "must be a valid CIDR notation" }

func CVV

func CVV(v string) bool

CVV reports whether or not v is a valid Card Verification Value.

valid:rule.yaml

name: cvv
error: { text: "must be a valid CVV" }

func Currency

func Currency(v string, code string, opts *CurrencyOpts) bool

Currency reports whether or not v represents a valid Currency amount.

valid:rule.yaml

name: ccy
args:
  - default: usd
  - default: null
error: { text: "must be a valid currency amount" }

func DataURI

func DataURI(v string) bool

DataURI reports whether or not v is a valid data URI.

valid:rule.yaml

name: datauri
error: { text: "must be a valid data URI" }

func Decimal

func Decimal(v string, locale string) bool

Decimal reports whether or not v represents a valid decimal number.

valid:rule.yaml

name: decimal
args: [{ default: en }]
error: { text: "string content must match a decimal number" }

func Digits

func Digits(v string) bool

Digits reports whether or not v is a string of digits.

valid:rule.yaml

name: digits
error: { text: "must contain only digits" }

func EAN

func EAN(v string) bool

EAN reports whether or not v is a valid European Article Number.

valid:rule.yaml

name: ean
error: { text: "must be a valid EAN" }

func ETH

func ETH(v string) bool

ETH reports whether or not v is a valid ethereum address.

valid:rule.yaml

name: eth
error: { text: "must be a valid ethereum address" }

func Email

func Email(v string) bool

Email reports whether or not v is a valid email address.

NOTE: Email uses "net/mail".ParseAddress to determine the validity of v.

valid:rule.yaml

name: email
error: { text: "must be a valid email address" }

func FQDN

func FQDN(v string) bool

FQDN reports whether or not v is a valid Fully Qualified Domain Name.

NOTE: FQDN TLD is required, numeric TLDs or trailing dots are disallowed, and underscores are forbidden.

valid:rule.yaml

name: fqdn
error: { text: "must be a valid FQDN" }

func Float

func Float(v string) bool

Float reports whether or not v represents a valid float.

valid:rule.yaml

name: float
error: { text: "string content must match a floating point number" }

func HSL

func HSL(v string) bool

HSL reports whether or not v represents an HSL color value.

valid:rule.yaml

name: hsl
error: { text: "must be a valid HSL color" }

func Hash

func Hash(v string, algo string) bool

Hash reports whether or not v is a hash of the specified algorithm.

valid:rule.yaml

name: hash
error: { text: "must be a valid hash" }

func Hex

func Hex(v string) bool

Hex reports whether or not v is a valid hexadecimal string.

valid:rule.yaml

name: hex
error: { text: "must be a valid hexadecimal string" }

func HexColor

func HexColor(v string) bool

HexColor reports whether or not v is a valid hexadecimal color code.

valid:rule.yaml

name: hexcolor
error: { text: "must represent a valid hexadecimal color code" }

func IBAN

func IBAN(v string) bool

IBAN reports whether or not v is an International Bank Account Number.

valid:rule.yaml

name: iban
error: { text: "must be a valid IBAN" }

func IMEI

func IMEI(v string) bool

IMEI reports whether or not v is an IMEI number.

valid:rule.yaml

name: imei
error: { text: "must be a valid IMEI number" }

func IP

func IP(v string, ver int) bool

IP reports whether or not v is a valid IP address. The ver argument specifies the IP's expected version. The ver argument can be one of the following three values:

0 accepts both IPv4 and IPv6
4 accepts IPv4 only
6 accepts IPv6 only

---

valid:rule.yaml

name: ip
args:
  - default: 0
    options:
      - { value: 4, alias: v4 }
      - { value: 6, alias: v6 }
error: { text: "must be a valid IP" }

func IPRange

func IPRange(v string) bool

IPRange reports whether or not v is a valid IP range (IPv4 only).

valid:rule.yaml

name: iprange
error: { text: "must be a valid IP range" }

func ISBN

func ISBN(v string, ver int) bool

ISBN reports whether or not v is a valid International Standard Book Number. The ver argument specifies the ISBN's expected version. The ver argument can be one of the following three values:

0 accepts both 10 and 13
10 accepts version 10 only
13 accepts version 13 only

---

valid:rule.yaml

name: isbn
args: [{ default: 0 }]
error: { text: "must be a valid ISBN" }

func ISIN

func ISIN(v string) bool

ISIN reports whether or not v is a valid International Securities Identification Number.

valid:rule.yaml

name: isin
error: { text: "must be a valid ISIN" }

func ISO31661A

func ISO31661A(v string, num int) bool

ISO31661A reports whether or not v is a valid country code as defined by the ISO 3166-1 Alpha standard. The num argument specifies which of the two alpha sets of the standard should be tested. The num argument can be one of the following three values:

0 tests against both Alpha-2 and Alpha-3
2 tests against Alpha-2 only
3 tests against Alpha-3 only

---

valid:rule.yaml

name: iso31661a
args: [{ default: 0 }]
error: { text: "must be a valid ISO 3166-1 Alpha value" }

func ISO4217

func ISO4217(v string) bool

ISO4217 reports whether or not v is a valid currency code as defined by the ISO 4217 standard.

valid:rule.yaml

name: iso4217
error: { text: "must be a valid ISO 4217 value" }

func ISO639

func ISO639(v string, num int) bool

ISO639 reports whether or not v is a valid language code as defined by the ISO 639 set of standards. Currently only standards 639-1 & 639-2 are supported. The num argument specifies which of the supported standards should be tested. The num argument can be one of the following three values:

0 tests against both 639-1 & 639-2
1 tests against 639-1 only
2 tests against 639-2 only

---

valid:rule.yaml

name: iso639
args: [{ default: 0 }]
error: { text: "must be a valid ISO 639 value" }

func ISRC

func ISRC(v string) bool

ISRC reports whether or not v is a valid International Standard Recording Code.

valid:rule.yaml

name: isrc
error: { text: "must be a valid ISRC" }

func ISSN

func ISSN(v string, requireHyphen, caseSensitive bool) bool

ISSN reports whether or not v is a valid International Standard Serial Number.

valid:rule.yaml

name: issn
error: { text: "must be a valid ISSN" }

func In

func In(v any, list ...any) bool

In reports whether or not v is in the provided list.

valid:rule.yaml

name: in
error: { text: "must be in the list" }

func Int

func Int(v string) bool

Int reports whether or not v represents a valid integer.

valid:rule.yaml

name: int
error: { text: "string content must match an integer" }

func JSON

func JSON(v []byte) bool

JSON reports whether or not v is a valid JSON value.

NOTE: the input is validated using json.Unmarshal which accepts primitive values as long as they are JSON values.

valid:rule.yaml

name: json
error: { text: "must be a valid JSON" }

func JWT

func JWT(v string) bool

JWT reports whether or not v is a valid JSON Web Token.

valid:rule.yaml

name: jwt
error: { text: "must be a valid JWT" }

func LatLong

func LatLong(v string, dms bool) bool

LatLong reports whether or not v is a valid latitude-longitude coordinate string.

valid:rule.yaml

name: latlong
args:
  - default: false
    options: [{ value: true, alias: dms }]
error: { text: "must be a valid latitude-longitude coordinate" }

func Locale

func Locale(v string) bool

Locale reports whether or not v is a valid locale.

valid:rule.yaml

name: locale
error: { text: "must be a valid locale" }

func LowerCase

func LowerCase(v string) bool

LowerCase reports whether or not v is an all lower-case string.

valid:rule.yaml

name: lower
error: { text: "must contain only lower-case characters" }

func MAC

func MAC(v string, space int) bool

MAC reports whether or not v is a valid MAC address. The space argument specifies the identifier's expected address space (in bytes). The space argument can be one of the following three values:

0 accepts both EUI-48 and EUI-64
6 accepts EUI-48 format only
8 accepts EUI-64 format only

The allowed formatting of the identifiers is as follows:

// EUI-48 format
"08:00:2b:01:02:03"
"08-00-2b-01-02-03"
"08002b010203"

// EUI-64 format
"08:00:2b:01:02:03:04:05"
"08-00-2b-01-02-03-04-05"
"08002b0102030405"

---

valid:rule.yaml

name: mac
args: [{ default: 0 }]
error: { text: "must be a valid MAC" }

func MD5

func MD5(v string) bool

MD5 reports whether or not v is a valid MD5 hash.

valid:rule.yaml

name: md5
error: { text: "must be a valid MD5 hash" }

func MIME

func MIME(v string) bool

MIME reports whether or not v is of a valid MIME type format.

NOTE: This function only checks is the string format follows the etablished rules by the according RFC specifications. This function supports 'charset' in textual media types (https://tools.ietf.org/html/rfc6657).

This function does not check against all the media types listed by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml)

More informations in the RFC specifications:

---

valid:rule.yaml

name: mime
error: { text: "must be a valid media type" }

func MagnetURI

func MagnetURI(v string) bool

MagnetURI reports whether or not v is a valid magned URI.

valid:rule.yaml

name: magneturi
error: { text: "must be a valid magnet URI" }

func Match

func Match(v string, expr string) bool

Match reports whether or not v contains any match of the *registered* regular expression expr.

NOTE: expr MUST be registered upfront with RegisterRegexp otherwise Match will return false even if v matches the regular expression.

valid:rule.yaml

name: re
error:
  text: "must match the regular expression"
  with_args: true

func MongoId

func MongoId(v string) bool

MongoId reports whether or not v is a valid hex-encoded representation of a MongoDB ObjectId.

valid:rule.yaml

name: mongoid
error: { text: "must be a valid Mongo Object Id" }

func Numeric

func Numeric(v string) bool

Numeric reports whether or not v is a valid numeric string.

valid:rule.yaml

name: numeric
error: { text: "string content must match a numeric value" }

func Octal

func Octal(v string) bool

Octal reports whether or not v represents a valid octal integer.

valid:rule.yaml

name: octal
error: { text: "string content must match an octal number" }

func PAN

func PAN(v string) bool

PAN reports whether or not v is a valid Primary Account Number or Credit Card number.

valid:rule.yaml

name: pan
error: { text: "must be a valid PAN" }

func Phone

func Phone(v string, cc string) bool

Phone reports whether or not v is a valid phone number in the country identified by the given country code cc.

valid:rule.yaml

name: phone
args: [{ default: us }]
error: { text: "must be a valid phone number" }

func Port

func Port(v string) bool

Port reports whether or not v is a valid port number.

valid:rule.yaml

name: port
error: { text: "must be a valid port number" }

func RGB

func RGB(v string) bool

RGB reports whether or not v is a valid RGB color.

valid:rule.yaml

name: rgb
error: { text: "must be a valid RGB color" }

func RegisterRegexp

func RegisterRegexp(expr string)

RegisterRegexp compiles the given expression and caches the result. The given expr is assumed to be a valid regular expression, if it's not then RegisterRegexp will panic.

func SSN

func SSN(v string) bool

SSN reports whether or not v has a valid Social Security Number format.

valid:rule.yaml

name: ssn
error: { text: "must be a valid SSN" }

func SemVer

func SemVer(v string) bool

SemVer reports whether or not v is a valid Semantic Versioning number. For reference: https://semver.org/

valid:rule.yaml

name: semver
error: { text: "must be a valid semver number" }

func Slug

func Slug(v string) bool

Slug reports whether or not v is a valid slug.

valid:rule.yaml

name: slug
error: { text: "must be a valid slug" }

func StrongPassword

func StrongPassword(v string, opts *StrongPasswordOpts) bool

StrongPassword reports whether or not v is a strong password.

valid:rule.yaml

name: strongpass
args: [{ default: null }]
error: { text: "must be a strong password" }

func UUID

func UUID(v string, ver int) bool

UUID reports whether or not v is a valid Universally Unique IDentifier. NOTE: only versions 3, 4, and 5 are currently supported.

valid:rule.yaml

name: uuid
args:
  - default: 4
    options:
      - { value: 3, alias: v3 }
      - { value: 4, alias: v4 }
      - { value: 5, alias: v5 }
error: { text: "must be a valid UUID" }

func Uint

func Uint(v string) bool

Uint reports whether or not v represents a valid unsigned integer.

valid:rule.yaml

name: uint
error: { text: "string content must match an unsigned integer" }

func UpperCase

func UpperCase(v string) bool

UpperCase reports whether or not v is an all upper-case string.

valid:rule.yaml

name: upper
error: { text: "must contain only upper-case characters" }

func VAT

func VAT(v string, cc string) bool

VAT reports whether or not v is a valid Value Added Tax number.

valid:rule.yaml

name: vat
args: [{ default: us }]
error: { text: "must be a valid VAT number" }

func Zip

func Zip(v string, cc string) bool

Zip reports whether or not v is a valid zip / postal code for the country identified by the given country code cc.

valid:rule.yaml

name: zip
args: [{ default: us }]
error: { text: "must be a valid zip code" }

Types

type CurrencyOpts

type CurrencyOpts struct {
	NeedSym bool
}

type StrongPasswordOpts

type StrongPasswordOpts struct {
	MinLen     int
	MinLower   int
	MinUpper   int
	MinNumbers int
	MinSymbols int
}

Directories

Path Synopsis
cmd
internal/search
package search is used to find targets for the generator.
package search is used to find targets for the generator.
internal

Jump to

Keyboard shortcuts

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