Skip to content

Repository files navigation

go-validator

GitHub release (latest SemVer)Go VersionGo Report CardGoDocMIT License

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings or use the fluent typed builder.

Installation

go get github.com/hymns/go-validator

Quick start

import validator "github.com/hymns/go-validator"v:=validator.Make(
validator.Input{
"email": "user@example.com",
"password": "secret",
"age": "17",
},
validator.Rules{
"email": "required|email",
"password": "required|min:8",
"age": "required|integer|min:18",
},
)
ifv.Fails() {
fmt.Println(v.Errors()) // map[age:["The age must be at least 18."] password:["The password must be at least 8 characters."]]
}

Or use the typed rule builder for compile-time safety and IDE autocompletion:

v:=validator.Make(input, validator.Rules{
"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
})

API

Make(input, rules) *Validator

Creates a validator. Validation is lazy — it runs on the first call to Fails(), Passes(), or Errors().

(*Validator).Messages(msgs) *Validator

Override error messages. Call before Fails() / Passes().

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Email address is mandatory.",
"email.email": "That doesn't look like a valid email.",
})

(*Validator).Bail() *Validator

Stop validation after the first field that produces an error (global bail). Useful when later fields depend on earlier ones passing.

v:=validator.Make(input, rules).Bail()

For per-field bail (stop checking remaining rules on that field on first failure), add bail to the rule string:

validator.Rules{
"email": "bail|required|email|unique:users,email",
// ↑ stops checking email rules on first failure
}

(*Validator).WithDB(db *sql.DB) *Validator

Attach a database connection for unique and exists rules.

(*Validator).Fails() bool

Returns true if validation failed.

(*Validator).Passes() bool

Returns true if validation passed.

(*Validator).Errors() ErrorBag

Returns all errors. ErrorBag is map[string][]string.

errs:=v.Errors()
errs.Has("email") // boolerrs.First("email") // string — first error message for the field

Rules

Rules are pipe-separated strings. Parameters are colon-separated from the rule name, and multiple parameters are comma-separated.

"required|string|min:3|max:100"
"required|in:admin,user,editor"
"required|unique:users,email"

Presence & required

RuleDescription
requiredField must be present and non-empty
nullableField may be nil; skips all other rules when nil
presentKey must exist in input (value may be empty)
filledIf key is present, value must not be empty
bailStop checking remaining rules for this field on first failure

Conditional required

RuleDescription
required_if:field,valueRequired when another field equals a value
required_unless:field,valueRequired unless another field equals a value
required_with:field1,field2Required when any of the listed fields is present
required_without:field1,field2Required when any of the listed fields is absent
required_with_all:field1,field2Required when all listed fields are present
required_without_all:field1,field2Required when all listed fields are absent

Prohibition

RuleDescription
prohibitedField must be absent or empty
prohibited_if:field,valueProhibited when another field equals a value
prohibited_unless:field,valueProhibited unless another field equals a value

Strings

RuleDescription
stringMust be a string
alphaLetters only (Unicode)
alpha_numLetters and numbers only
alpha_dashLetters, numbers, hyphens, and underscores
emailValid email format
urlValid URL (http/https)
active_urlURL with resolvable host
uuidValid UUID (any version)
ulidValid ULID
hex_colorHex color code (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)
jsonValid JSON string
lowercaseAll lowercase
uppercaseAll uppercase
starts_with:a,bMust start with one of the given values
ends_with:a,bMust end with one of the given values
doesnt_start_with:a,bMust not start with any of the given values
doesnt_end_with:a,bMust not end with any of the given values
regex:patternMust match the regex pattern
not_regex:patternMust not match the regex pattern
same:fieldMust match another field's value
different:fieldMust differ from another field's value
confirmedMust have a matching {field}_confirmation field

Note: Regex patterns cannot contain | (the rule separator). Use Extend() for complex patterns.

Numeric

RuleDescription
integerMust be an integer
numericMust be numeric (int or float)
decimal:min,maxMust have between min and max decimal places
digits:nExactly n digits
digits_between:min,maxBetween min and max digits
multiple_of:nMust be a multiple of n
min:nMinimum value (numeric) or minimum length (string/array)
max:nMaximum value (numeric) or maximum length (string/array)
between:min,maxBetween min and max (numeric or string length)
size:nExact size — character count for strings, item count for arrays, numeric value
gt:n or gt:fieldGreater than value or another field
gte:n or gte:fieldGreater than or equal
lt:n or lt:fieldLess than value or another field
lte:n or lte:fieldLess than or equal

Boolean

RuleDescription
booleanMust be a boolean-like value (true, false, 1, 0, "1", "0")
acceptedMust be an accepted value (yes, on, 1, true)
declinedMust be a declined value (no, off, 0, false)
accepted_if:field,valueMust be accepted when another field equals a value
declined_if:field,valueMust be declined when another field equals a value

Dates

Supported date layouts: 2006-01-02, 02/01/2006, 01/02/2006, 2006-01-02 15:04:05, 2006-01-02T15:04:05Z07:00.

RuleDescription
dateValid date string
date_format:layoutMatches the given Go time layout
date_equals:dateEquals the given date
before:dateMust be before the given date
before_or_equal:dateMust be before or equal to the given date
after:dateMust be after the given date
after_or_equal:dateMust be after or equal to the given date
timezoneValid IANA timezone name (e.g. Asia/Kuala_Lumpur)

Network

RuleDescription
ipValid IPv4 or IPv6 address
ipv4Valid IPv4 address
ipv6Valid IPv6 address
mac_addressValid MAC address (colon or hyphen separated)

Arrays

RuleDescription
arrayMust be a []any
distinctArray items must be unique
in:a,b,cValue must be one of the listed values
not_in:a,b,cValue must not be one of the listed values

Database

Requires .WithDB(db). Returns a db_required error if no DB is attached.

RuleDescription
unique:table,columnValue must not exist in the given column
unique:table,column,ignoreValue,ignoreColumnUnique but ignore a specific row (for updates)
exists:table,columnValue must exist in the given column
// On create"email": "required|email|unique:users,email"// On update — ignore the current user's row"email": "required|email|unique:users,email,42,id"

ignoreColumn defaults to id if omitted.

Custom messages

Override any message globally with field.rule keys, or just rule for field-agnostic overrides.

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Please provide your email.",
"email.email": "That email address is not valid.",
"password.min": "Password needs at least :param characters.",
})

Available placeholders: :field, :param, :other, :value, :min, :max.

Typed rule builder

R() returns a *RuleBuilder. Chain methods, then call Build() to produce the pipe-separated string. Both styles are fully compatible with Make().

validator.Rules{
// string style"email": "required|email|max:100",
// typed builder — compile-safe, IDE autocomplete"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
"slug": validator.R().Required().Regex(`^[a-z0-9-]+$`).Build(),
"score": validator.R().Required().Numeric().Between(0, 100).Build(),
}

Every built-in rule has a corresponding method. A few naming notes:

Rule stringBuilder method
string.Str() (reserved word in Go)
required_if:field,val.RequiredIf("field", "val")
starts_with:a,b.StartsWith("a", "b")
in:a,b,c.In("a", "b", "c")
unique:users,email.Unique("users", "email")

Nested validation

Use dot notation to validate fields inside nested maps:

// Input
{
"user": {
"name": "hamizi",
"address": {
"postcode": "50000"
}
}
}
// Rulesvalidator.Make(input, validator.Rules{
"user.name": "required|min:3",
"user.address.postcode": "required|digits:5",
})

Array wildcard

Use field.* to validate every element of an array. Errors are keyed as field.0, field.1, etc.

// Input
{
"tags": ["laravel", "golang", ""]
}
// Rulesvalidator.Make(input, validator.Rules{
"tags": "required|array",
"tags.*": "required|string|min:2",
})
// Errors// tags.2 → ["The tags.2 field is required."]

Custom rules

Register reusable rules with Extend:

validator.Extend("strong_password", func(fieldstring, valueany, paramstring) error {
s, ok:=value.(string)
if!ok||len(s) <12 {
returnfmt.Errorf("The %s must be at least 12 characters.", field)
}
returnnil
})
// Use it like any built-in rulevalidator.Make(input, validator.Rules{
"password": "required|strong_password",
})

Usage with Fiber

funcCreateUser(c*fiber.Ctx) error {
varbodymap[string]anyiferr:=c.BodyParser(&body); err!=nil {
returnc.Status(400).JSON(fiber.Map{"error": "invalid body"})
}
v:=validator.Make(validator.Input(body), validator.Rules{
"name": "required|string|min:2|max:100",
"email": "required|email|unique:users,email",
"password": "required|min:8|confirmed",
"role": "required|in:admin,user,editor",
}).WithDB(db)
ifv.Fails() {
returnc.Status(422).JSON(v.Errors())
}
// proceed with validated input ...returnc.SendStatus(201)
}

Testing

# Run all tests
go test ./tests/...
# Verbose
go test ./tests/... -v

License

Distributed under MIT License, please see license file within the code for more details.

About

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - hymns/go-validator: A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings. · GitHub
Skip to content

Repository files navigation

go-validator

GitHub release (latest SemVer)Go VersionGo Report CardGoDocMIT License

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings or use the fluent typed builder.

Installation

go get github.com/hymns/go-validator

Quick start

import validator "github.com/hymns/go-validator"v:=validator.Make(
validator.Input{
"email": "user@example.com",
"password": "secret",
"age": "17",
},
validator.Rules{
"email": "required|email",
"password": "required|min:8",
"age": "required|integer|min:18",
},
)
ifv.Fails() {
fmt.Println(v.Errors()) // map[age:["The age must be at least 18."] password:["The password must be at least 8 characters."]]
}

Or use the typed rule builder for compile-time safety and IDE autocompletion:

v:=validator.Make(input, validator.Rules{
"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
})

API

Make(input, rules) *Validator

Creates a validator. Validation is lazy — it runs on the first call to Fails(), Passes(), or Errors().

(*Validator).Messages(msgs) *Validator

Override error messages. Call before Fails() / Passes().

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Email address is mandatory.",
"email.email": "That doesn't look like a valid email.",
})

(*Validator).Bail() *Validator

Stop validation after the first field that produces an error (global bail). Useful when later fields depend on earlier ones passing.

v:=validator.Make(input, rules).Bail()

For per-field bail (stop checking remaining rules on that field on first failure), add bail to the rule string:

validator.Rules{
"email": "bail|required|email|unique:users,email",
// ↑ stops checking email rules on first failure
}

(*Validator).WithDB(db *sql.DB) *Validator

Attach a database connection for unique and exists rules.

(*Validator).Fails() bool

Returns true if validation failed.

(*Validator).Passes() bool

Returns true if validation passed.

(*Validator).Errors() ErrorBag

Returns all errors. ErrorBag is map[string][]string.

errs:=v.Errors()
errs.Has("email") // boolerrs.First("email") // string — first error message for the field

Rules

Rules are pipe-separated strings. Parameters are colon-separated from the rule name, and multiple parameters are comma-separated.

"required|string|min:3|max:100"
"required|in:admin,user,editor"
"required|unique:users,email"

Presence & required

RuleDescription
requiredField must be present and non-empty
nullableField may be nil; skips all other rules when nil
presentKey must exist in input (value may be empty)
filledIf key is present, value must not be empty
bailStop checking remaining rules for this field on first failure

Conditional required

RuleDescription
required_if:field,valueRequired when another field equals a value
required_unless:field,valueRequired unless another field equals a value
required_with:field1,field2Required when any of the listed fields is present
required_without:field1,field2Required when any of the listed fields is absent
required_with_all:field1,field2Required when all listed fields are present
required_without_all:field1,field2Required when all listed fields are absent

Prohibition

RuleDescription
prohibitedField must be absent or empty
prohibited_if:field,valueProhibited when another field equals a value
prohibited_unless:field,valueProhibited unless another field equals a value

Strings

RuleDescription
stringMust be a string
alphaLetters only (Unicode)
alpha_numLetters and numbers only
alpha_dashLetters, numbers, hyphens, and underscores
emailValid email format
urlValid URL (http/https)
active_urlURL with resolvable host
uuidValid UUID (any version)
ulidValid ULID
hex_colorHex color code (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)
jsonValid JSON string
lowercaseAll lowercase
uppercaseAll uppercase
starts_with:a,bMust start with one of the given values
ends_with:a,bMust end with one of the given values
doesnt_start_with:a,bMust not start with any of the given values
doesnt_end_with:a,bMust not end with any of the given values
regex:patternMust match the regex pattern
not_regex:patternMust not match the regex pattern
same:fieldMust match another field's value
different:fieldMust differ from another field's value
confirmedMust have a matching {field}_confirmation field

Note: Regex patterns cannot contain | (the rule separator). Use Extend() for complex patterns.

Numeric

RuleDescription
integerMust be an integer
numericMust be numeric (int or float)
decimal:min,maxMust have between min and max decimal places
digits:nExactly n digits
digits_between:min,maxBetween min and max digits
multiple_of:nMust be a multiple of n
min:nMinimum value (numeric) or minimum length (string/array)
max:nMaximum value (numeric) or maximum length (string/array)
between:min,maxBetween min and max (numeric or string length)
size:nExact size — character count for strings, item count for arrays, numeric value
gt:n or gt:fieldGreater than value or another field
gte:n or gte:fieldGreater than or equal
lt:n or lt:fieldLess than value or another field
lte:n or lte:fieldLess than or equal

Boolean

RuleDescription
booleanMust be a boolean-like value (true, false, 1, 0, "1", "0")
acceptedMust be an accepted value (yes, on, 1, true)
declinedMust be a declined value (no, off, 0, false)
accepted_if:field,valueMust be accepted when another field equals a value
declined_if:field,valueMust be declined when another field equals a value

Dates

Supported date layouts: 2006-01-02, 02/01/2006, 01/02/2006, 2006-01-02 15:04:05, 2006-01-02T15:04:05Z07:00.

RuleDescription
dateValid date string
date_format:layoutMatches the given Go time layout
date_equals:dateEquals the given date
before:dateMust be before the given date
before_or_equal:dateMust be before or equal to the given date
after:dateMust be after the given date
after_or_equal:dateMust be after or equal to the given date
timezoneValid IANA timezone name (e.g. Asia/Kuala_Lumpur)

Network

RuleDescription
ipValid IPv4 or IPv6 address
ipv4Valid IPv4 address
ipv6Valid IPv6 address
mac_addressValid MAC address (colon or hyphen separated)

Arrays

RuleDescription
arrayMust be a []any
distinctArray items must be unique
in:a,b,cValue must be one of the listed values
not_in:a,b,cValue must not be one of the listed values

Database

Requires .WithDB(db). Returns a db_required error if no DB is attached.

RuleDescription
unique:table,columnValue must not exist in the given column
unique:table,column,ignoreValue,ignoreColumnUnique but ignore a specific row (for updates)
exists:table,columnValue must exist in the given column
// On create"email": "required|email|unique:users,email"// On update — ignore the current user's row"email": "required|email|unique:users,email,42,id"

ignoreColumn defaults to id if omitted.

Custom messages

Override any message globally with field.rule keys, or just rule for field-agnostic overrides.

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Please provide your email.",
"email.email": "That email address is not valid.",
"password.min": "Password needs at least :param characters.",
})

Available placeholders: :field, :param, :other, :value, :min, :max.

Typed rule builder

R() returns a *RuleBuilder. Chain methods, then call Build() to produce the pipe-separated string. Both styles are fully compatible with Make().

validator.Rules{
// string style"email": "required|email|max:100",
// typed builder — compile-safe, IDE autocomplete"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
"slug": validator.R().Required().Regex(`^[a-z0-9-]+$`).Build(),
"score": validator.R().Required().Numeric().Between(0, 100).Build(),
}

Every built-in rule has a corresponding method. A few naming notes:

Rule stringBuilder method
string.Str() (reserved word in Go)
required_if:field,val.RequiredIf("field", "val")
starts_with:a,b.StartsWith("a", "b")
in:a,b,c.In("a", "b", "c")
unique:users,email.Unique("users", "email")

Nested validation

Use dot notation to validate fields inside nested maps:

// Input
{
"user": {
"name": "hamizi",
"address": {
"postcode": "50000"
}
}
}
// Rulesvalidator.Make(input, validator.Rules{
"user.name": "required|min:3",
"user.address.postcode": "required|digits:5",
})

Array wildcard

Use field.* to validate every element of an array. Errors are keyed as field.0, field.1, etc.

// Input
{
"tags": ["laravel", "golang", ""]
}
// Rulesvalidator.Make(input, validator.Rules{
"tags": "required|array",
"tags.*": "required|string|min:2",
})
// Errors// tags.2 → ["The tags.2 field is required."]

Custom rules

Register reusable rules with Extend:

validator.Extend("strong_password", func(fieldstring, valueany, paramstring) error {
s, ok:=value.(string)
if!ok||len(s) <12 {
returnfmt.Errorf("The %s must be at least 12 characters.", field)
}
returnnil
})
// Use it like any built-in rulevalidator.Make(input, validator.Rules{
"password": "required|strong_password",
})

Usage with Fiber

funcCreateUser(c*fiber.Ctx) error {
varbodymap[string]anyiferr:=c.BodyParser(&body); err!=nil {
returnc.Status(400).JSON(fiber.Map{"error": "invalid body"})
}
v:=validator.Make(validator.Input(body), validator.Rules{
"name": "required|string|min:2|max:100",
"email": "required|email|unique:users,email",
"password": "required|min:8|confirmed",
"role": "required|in:admin,user,editor",
}).WithDB(db)
ifv.Fails() {
returnc.Status(422).JSON(v.Errors())
}
// proceed with validated input ...returnc.SendStatus(201)
}

Testing

# Run all tests
go test ./tests/...
# Verbose
go test ./tests/... -v

License

Distributed under MIT License, please see license file within the code for more details.

About

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - hymns/go-validator: A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings. · GitHub
Skip to content

Repository files navigation

go-validator

GitHub release (latest SemVer)Go VersionGo Report CardGoDocMIT License

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings or use the fluent typed builder.

Installation

go get github.com/hymns/go-validator

Quick start

import validator "github.com/hymns/go-validator"v:=validator.Make(
validator.Input{
"email": "user@example.com",
"password": "secret",
"age": "17",
},
validator.Rules{
"email": "required|email",
"password": "required|min:8",
"age": "required|integer|min:18",
},
)
ifv.Fails() {
fmt.Println(v.Errors()) // map[age:["The age must be at least 18."] password:["The password must be at least 8 characters."]]
}

Or use the typed rule builder for compile-time safety and IDE autocompletion:

v:=validator.Make(input, validator.Rules{
"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
})

API

Make(input, rules) *Validator

Creates a validator. Validation is lazy — it runs on the first call to Fails(), Passes(), or Errors().

(*Validator).Messages(msgs) *Validator

Override error messages. Call before Fails() / Passes().

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Email address is mandatory.",
"email.email": "That doesn't look like a valid email.",
})

(*Validator).Bail() *Validator

Stop validation after the first field that produces an error (global bail). Useful when later fields depend on earlier ones passing.

v:=validator.Make(input, rules).Bail()

For per-field bail (stop checking remaining rules on that field on first failure), add bail to the rule string:

validator.Rules{
"email": "bail|required|email|unique:users,email",
// ↑ stops checking email rules on first failure
}

(*Validator).WithDB(db *sql.DB) *Validator

Attach a database connection for unique and exists rules.

(*Validator).Fails() bool

Returns true if validation failed.

(*Validator).Passes() bool

Returns true if validation passed.

(*Validator).Errors() ErrorBag

Returns all errors. ErrorBag is map[string][]string.

errs:=v.Errors()
errs.Has("email") // boolerrs.First("email") // string — first error message for the field

Rules

Rules are pipe-separated strings. Parameters are colon-separated from the rule name, and multiple parameters are comma-separated.

"required|string|min:3|max:100"
"required|in:admin,user,editor"
"required|unique:users,email"

Presence & required

RuleDescription
requiredField must be present and non-empty
nullableField may be nil; skips all other rules when nil
presentKey must exist in input (value may be empty)
filledIf key is present, value must not be empty
bailStop checking remaining rules for this field on first failure

Conditional required

RuleDescription
required_if:field,valueRequired when another field equals a value
required_unless:field,valueRequired unless another field equals a value
required_with:field1,field2Required when any of the listed fields is present
required_without:field1,field2Required when any of the listed fields is absent
required_with_all:field1,field2Required when all listed fields are present
required_without_all:field1,field2Required when all listed fields are absent

Prohibition

RuleDescription
prohibitedField must be absent or empty
prohibited_if:field,valueProhibited when another field equals a value
prohibited_unless:field,valueProhibited unless another field equals a value

Strings

RuleDescription
stringMust be a string
alphaLetters only (Unicode)
alpha_numLetters and numbers only
alpha_dashLetters, numbers, hyphens, and underscores
emailValid email format
urlValid URL (http/https)
active_urlURL with resolvable host
uuidValid UUID (any version)
ulidValid ULID
hex_colorHex color code (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)
jsonValid JSON string
lowercaseAll lowercase
uppercaseAll uppercase
starts_with:a,bMust start with one of the given values
ends_with:a,bMust end with one of the given values
doesnt_start_with:a,bMust not start with any of the given values
doesnt_end_with:a,bMust not end with any of the given values
regex:patternMust match the regex pattern
not_regex:patternMust not match the regex pattern
same:fieldMust match another field's value
different:fieldMust differ from another field's value
confirmedMust have a matching {field}_confirmation field

Note: Regex patterns cannot contain | (the rule separator). Use Extend() for complex patterns.

Numeric

RuleDescription
integerMust be an integer
numericMust be numeric (int or float)
decimal:min,maxMust have between min and max decimal places
digits:nExactly n digits
digits_between:min,maxBetween min and max digits
multiple_of:nMust be a multiple of n
min:nMinimum value (numeric) or minimum length (string/array)
max:nMaximum value (numeric) or maximum length (string/array)
between:min,maxBetween min and max (numeric or string length)
size:nExact size — character count for strings, item count for arrays, numeric value
gt:n or gt:fieldGreater than value or another field
gte:n or gte:fieldGreater than or equal
lt:n or lt:fieldLess than value or another field
lte:n or lte:fieldLess than or equal

Boolean

RuleDescription
booleanMust be a boolean-like value (true, false, 1, 0, "1", "0")
acceptedMust be an accepted value (yes, on, 1, true)
declinedMust be a declined value (no, off, 0, false)
accepted_if:field,valueMust be accepted when another field equals a value
declined_if:field,valueMust be declined when another field equals a value

Dates

Supported date layouts: 2006-01-02, 02/01/2006, 01/02/2006, 2006-01-02 15:04:05, 2006-01-02T15:04:05Z07:00.

RuleDescription
dateValid date string
date_format:layoutMatches the given Go time layout
date_equals:dateEquals the given date
before:dateMust be before the given date
before_or_equal:dateMust be before or equal to the given date
after:dateMust be after the given date
after_or_equal:dateMust be after or equal to the given date
timezoneValid IANA timezone name (e.g. Asia/Kuala_Lumpur)

Network

RuleDescription
ipValid IPv4 or IPv6 address
ipv4Valid IPv4 address
ipv6Valid IPv6 address
mac_addressValid MAC address (colon or hyphen separated)

Arrays

RuleDescription
arrayMust be a []any
distinctArray items must be unique
in:a,b,cValue must be one of the listed values
not_in:a,b,cValue must not be one of the listed values

Database

Requires .WithDB(db). Returns a db_required error if no DB is attached.

RuleDescription
unique:table,columnValue must not exist in the given column
unique:table,column,ignoreValue,ignoreColumnUnique but ignore a specific row (for updates)
exists:table,columnValue must exist in the given column
// On create"email": "required|email|unique:users,email"// On update — ignore the current user's row"email": "required|email|unique:users,email,42,id"

ignoreColumn defaults to id if omitted.

Custom messages

Override any message globally with field.rule keys, or just rule for field-agnostic overrides.

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Please provide your email.",
"email.email": "That email address is not valid.",
"password.min": "Password needs at least :param characters.",
})

Available placeholders: :field, :param, :other, :value, :min, :max.

Typed rule builder

R() returns a *RuleBuilder. Chain methods, then call Build() to produce the pipe-separated string. Both styles are fully compatible with Make().

validator.Rules{
// string style"email": "required|email|max:100",
// typed builder — compile-safe, IDE autocomplete"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
"slug": validator.R().Required().Regex(`^[a-z0-9-]+$`).Build(),
"score": validator.R().Required().Numeric().Between(0, 100).Build(),
}

Every built-in rule has a corresponding method. A few naming notes:

Rule stringBuilder method
string.Str() (reserved word in Go)
required_if:field,val.RequiredIf("field", "val")
starts_with:a,b.StartsWith("a", "b")
in:a,b,c.In("a", "b", "c")
unique:users,email.Unique("users", "email")

Nested validation

Use dot notation to validate fields inside nested maps:

// Input
{
"user": {
"name": "hamizi",
"address": {
"postcode": "50000"
}
}
}
// Rulesvalidator.Make(input, validator.Rules{
"user.name": "required|min:3",
"user.address.postcode": "required|digits:5",
})

Array wildcard

Use field.* to validate every element of an array. Errors are keyed as field.0, field.1, etc.

// Input
{
"tags": ["laravel", "golang", ""]
}
// Rulesvalidator.Make(input, validator.Rules{
"tags": "required|array",
"tags.*": "required|string|min:2",
})
// Errors// tags.2 → ["The tags.2 field is required."]

Custom rules

Register reusable rules with Extend:

validator.Extend("strong_password", func(fieldstring, valueany, paramstring) error {
s, ok:=value.(string)
if!ok||len(s) <12 {
returnfmt.Errorf("The %s must be at least 12 characters.", field)
}
returnnil
})
// Use it like any built-in rulevalidator.Make(input, validator.Rules{
"password": "required|strong_password",
})

Usage with Fiber

funcCreateUser(c*fiber.Ctx) error {
varbodymap[string]anyiferr:=c.BodyParser(&body); err!=nil {
returnc.Status(400).JSON(fiber.Map{"error": "invalid body"})
}
v:=validator.Make(validator.Input(body), validator.Rules{
"name": "required|string|min:2|max:100",
"email": "required|email|unique:users,email",
"password": "required|min:8|confirmed",
"role": "required|in:admin,user,editor",
}).WithDB(db)
ifv.Fails() {
returnc.Status(422).JSON(v.Errors())
}
// proceed with validated input ...returnc.SendStatus(201)
}

Testing

# Run all tests
go test ./tests/...
# Verbose
go test ./tests/... -v

License

Distributed under MIT License, please see license file within the code for more details.

About

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - hymns/go-validator: A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings. · GitHub
Skip to content

Repository files navigation

go-validator

GitHub release (latest SemVer)Go VersionGo Report CardGoDocMIT License

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings or use the fluent typed builder.

Installation

go get github.com/hymns/go-validator

Quick start

import validator "github.com/hymns/go-validator"v:=validator.Make(
validator.Input{
"email": "user@example.com",
"password": "secret",
"age": "17",
},
validator.Rules{
"email": "required|email",
"password": "required|min:8",
"age": "required|integer|min:18",
},
)
ifv.Fails() {
fmt.Println(v.Errors()) // map[age:["The age must be at least 18."] password:["The password must be at least 8 characters."]]
}

Or use the typed rule builder for compile-time safety and IDE autocompletion:

v:=validator.Make(input, validator.Rules{
"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
})

API

Make(input, rules) *Validator

Creates a validator. Validation is lazy — it runs on the first call to Fails(), Passes(), or Errors().

(*Validator).Messages(msgs) *Validator

Override error messages. Call before Fails() / Passes().

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Email address is mandatory.",
"email.email": "That doesn't look like a valid email.",
})

(*Validator).Bail() *Validator

Stop validation after the first field that produces an error (global bail). Useful when later fields depend on earlier ones passing.

v:=validator.Make(input, rules).Bail()

For per-field bail (stop checking remaining rules on that field on first failure), add bail to the rule string:

validator.Rules{
"email": "bail|required|email|unique:users,email",
// ↑ stops checking email rules on first failure
}

(*Validator).WithDB(db *sql.DB) *Validator

Attach a database connection for unique and exists rules.

(*Validator).Fails() bool

Returns true if validation failed.

(*Validator).Passes() bool

Returns true if validation passed.

(*Validator).Errors() ErrorBag

Returns all errors. ErrorBag is map[string][]string.

errs:=v.Errors()
errs.Has("email") // boolerrs.First("email") // string — first error message for the field

Rules

Rules are pipe-separated strings. Parameters are colon-separated from the rule name, and multiple parameters are comma-separated.

"required|string|min:3|max:100"
"required|in:admin,user,editor"
"required|unique:users,email"

Presence & required

RuleDescription
requiredField must be present and non-empty
nullableField may be nil; skips all other rules when nil
presentKey must exist in input (value may be empty)
filledIf key is present, value must not be empty
bailStop checking remaining rules for this field on first failure

Conditional required

RuleDescription
required_if:field,valueRequired when another field equals a value
required_unless:field,valueRequired unless another field equals a value
required_with:field1,field2Required when any of the listed fields is present
required_without:field1,field2Required when any of the listed fields is absent
required_with_all:field1,field2Required when all listed fields are present
required_without_all:field1,field2Required when all listed fields are absent

Prohibition

RuleDescription
prohibitedField must be absent or empty
prohibited_if:field,valueProhibited when another field equals a value
prohibited_unless:field,valueProhibited unless another field equals a value

Strings

RuleDescription
stringMust be a string
alphaLetters only (Unicode)
alpha_numLetters and numbers only
alpha_dashLetters, numbers, hyphens, and underscores
emailValid email format
urlValid URL (http/https)
active_urlURL with resolvable host
uuidValid UUID (any version)
ulidValid ULID
hex_colorHex color code (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)
jsonValid JSON string
lowercaseAll lowercase
uppercaseAll uppercase
starts_with:a,bMust start with one of the given values
ends_with:a,bMust end with one of the given values
doesnt_start_with:a,bMust not start with any of the given values
doesnt_end_with:a,bMust not end with any of the given values
regex:patternMust match the regex pattern
not_regex:patternMust not match the regex pattern
same:fieldMust match another field's value
different:fieldMust differ from another field's value
confirmedMust have a matching {field}_confirmation field

Note: Regex patterns cannot contain | (the rule separator). Use Extend() for complex patterns.

Numeric

RuleDescription
integerMust be an integer
numericMust be numeric (int or float)
decimal:min,maxMust have between min and max decimal places
digits:nExactly n digits
digits_between:min,maxBetween min and max digits
multiple_of:nMust be a multiple of n
min:nMinimum value (numeric) or minimum length (string/array)
max:nMaximum value (numeric) or maximum length (string/array)
between:min,maxBetween min and max (numeric or string length)
size:nExact size — character count for strings, item count for arrays, numeric value
gt:n or gt:fieldGreater than value or another field
gte:n or gte:fieldGreater than or equal
lt:n or lt:fieldLess than value or another field
lte:n or lte:fieldLess than or equal

Boolean

RuleDescription
booleanMust be a boolean-like value (true, false, 1, 0, "1", "0")
acceptedMust be an accepted value (yes, on, 1, true)
declinedMust be a declined value (no, off, 0, false)
accepted_if:field,valueMust be accepted when another field equals a value
declined_if:field,valueMust be declined when another field equals a value

Dates

Supported date layouts: 2006-01-02, 02/01/2006, 01/02/2006, 2006-01-02 15:04:05, 2006-01-02T15:04:05Z07:00.

RuleDescription
dateValid date string
date_format:layoutMatches the given Go time layout
date_equals:dateEquals the given date
before:dateMust be before the given date
before_or_equal:dateMust be before or equal to the given date
after:dateMust be after the given date
after_or_equal:dateMust be after or equal to the given date
timezoneValid IANA timezone name (e.g. Asia/Kuala_Lumpur)

Network

RuleDescription
ipValid IPv4 or IPv6 address
ipv4Valid IPv4 address
ipv6Valid IPv6 address
mac_addressValid MAC address (colon or hyphen separated)

Arrays

RuleDescription
arrayMust be a []any
distinctArray items must be unique
in:a,b,cValue must be one of the listed values
not_in:a,b,cValue must not be one of the listed values

Database

Requires .WithDB(db). Returns a db_required error if no DB is attached.

RuleDescription
unique:table,columnValue must not exist in the given column
unique:table,column,ignoreValue,ignoreColumnUnique but ignore a specific row (for updates)
exists:table,columnValue must exist in the given column
// On create"email": "required|email|unique:users,email"// On update — ignore the current user's row"email": "required|email|unique:users,email,42,id"

ignoreColumn defaults to id if omitted.

Custom messages

Override any message globally with field.rule keys, or just rule for field-agnostic overrides.

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Please provide your email.",
"email.email": "That email address is not valid.",
"password.min": "Password needs at least :param characters.",
})

Available placeholders: :field, :param, :other, :value, :min, :max.

Typed rule builder

R() returns a *RuleBuilder. Chain methods, then call Build() to produce the pipe-separated string. Both styles are fully compatible with Make().

validator.Rules{
// string style"email": "required|email|max:100",
// typed builder — compile-safe, IDE autocomplete"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
"slug": validator.R().Required().Regex(`^[a-z0-9-]+$`).Build(),
"score": validator.R().Required().Numeric().Between(0, 100).Build(),
}

Every built-in rule has a corresponding method. A few naming notes:

Rule stringBuilder method
string.Str() (reserved word in Go)
required_if:field,val.RequiredIf("field", "val")
starts_with:a,b.StartsWith("a", "b")
in:a,b,c.In("a", "b", "c")
unique:users,email.Unique("users", "email")

Nested validation

Use dot notation to validate fields inside nested maps:

// Input
{
"user": {
"name": "hamizi",
"address": {
"postcode": "50000"
}
}
}
// Rulesvalidator.Make(input, validator.Rules{
"user.name": "required|min:3",
"user.address.postcode": "required|digits:5",
})

Array wildcard

Use field.* to validate every element of an array. Errors are keyed as field.0, field.1, etc.

// Input
{
"tags": ["laravel", "golang", ""]
}
// Rulesvalidator.Make(input, validator.Rules{
"tags": "required|array",
"tags.*": "required|string|min:2",
})
// Errors// tags.2 → ["The tags.2 field is required."]

Custom rules

Register reusable rules with Extend:

validator.Extend("strong_password", func(fieldstring, valueany, paramstring) error {
s, ok:=value.(string)
if!ok||len(s) <12 {
returnfmt.Errorf("The %s must be at least 12 characters.", field)
}
returnnil
})
// Use it like any built-in rulevalidator.Make(input, validator.Rules{
"password": "required|strong_password",
})

Usage with Fiber

funcCreateUser(c*fiber.Ctx) error {
varbodymap[string]anyiferr:=c.BodyParser(&body); err!=nil {
returnc.Status(400).JSON(fiber.Map{"error": "invalid body"})
}
v:=validator.Make(validator.Input(body), validator.Rules{
"name": "required|string|min:2|max:100",
"email": "required|email|unique:users,email",
"password": "required|min:8|confirmed",
"role": "required|in:admin,user,editor",
}).WithDB(db)
ifv.Fails() {
returnc.Status(422).JSON(v.Errors())
}
// proceed with validated input ...returnc.SendStatus(201)
}

Testing

# Run all tests
go test ./tests/...
# Verbose
go test ./tests/... -v

License

Distributed under MIT License, please see license file within the code for more details.

About

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - hymns/go-validator: A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings. · GitHub
Skip to content

Repository files navigation

go-validator

GitHub release (latest SemVer)Go VersionGo Report CardGoDocMIT License

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings or use the fluent typed builder.

Installation

go get github.com/hymns/go-validator

Quick start

import validator "github.com/hymns/go-validator"v:=validator.Make(
validator.Input{
"email": "user@example.com",
"password": "secret",
"age": "17",
},
validator.Rules{
"email": "required|email",
"password": "required|min:8",
"age": "required|integer|min:18",
},
)
ifv.Fails() {
fmt.Println(v.Errors()) // map[age:["The age must be at least 18."] password:["The password must be at least 8 characters."]]
}

Or use the typed rule builder for compile-time safety and IDE autocompletion:

v:=validator.Make(input, validator.Rules{
"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
})

API

Make(input, rules) *Validator

Creates a validator. Validation is lazy — it runs on the first call to Fails(), Passes(), or Errors().

(*Validator).Messages(msgs) *Validator

Override error messages. Call before Fails() / Passes().

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Email address is mandatory.",
"email.email": "That doesn't look like a valid email.",
})

(*Validator).Bail() *Validator

Stop validation after the first field that produces an error (global bail). Useful when later fields depend on earlier ones passing.

v:=validator.Make(input, rules).Bail()

For per-field bail (stop checking remaining rules on that field on first failure), add bail to the rule string:

validator.Rules{
"email": "bail|required|email|unique:users,email",
// ↑ stops checking email rules on first failure
}

(*Validator).WithDB(db *sql.DB) *Validator

Attach a database connection for unique and exists rules.

(*Validator).Fails() bool

Returns true if validation failed.

(*Validator).Passes() bool

Returns true if validation passed.

(*Validator).Errors() ErrorBag

Returns all errors. ErrorBag is map[string][]string.

errs:=v.Errors()
errs.Has("email") // boolerrs.First("email") // string — first error message for the field

Rules

Rules are pipe-separated strings. Parameters are colon-separated from the rule name, and multiple parameters are comma-separated.

"required|string|min:3|max:100"
"required|in:admin,user,editor"
"required|unique:users,email"

Presence & required

RuleDescription
requiredField must be present and non-empty
nullableField may be nil; skips all other rules when nil
presentKey must exist in input (value may be empty)
filledIf key is present, value must not be empty
bailStop checking remaining rules for this field on first failure

Conditional required

RuleDescription
required_if:field,valueRequired when another field equals a value
required_unless:field,valueRequired unless another field equals a value
required_with:field1,field2Required when any of the listed fields is present
required_without:field1,field2Required when any of the listed fields is absent
required_with_all:field1,field2Required when all listed fields are present
required_without_all:field1,field2Required when all listed fields are absent

Prohibition

RuleDescription
prohibitedField must be absent or empty
prohibited_if:field,valueProhibited when another field equals a value
prohibited_unless:field,valueProhibited unless another field equals a value

Strings

RuleDescription
stringMust be a string
alphaLetters only (Unicode)
alpha_numLetters and numbers only
alpha_dashLetters, numbers, hyphens, and underscores
emailValid email format
urlValid URL (http/https)
active_urlURL with resolvable host
uuidValid UUID (any version)
ulidValid ULID
hex_colorHex color code (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)
jsonValid JSON string
lowercaseAll lowercase
uppercaseAll uppercase
starts_with:a,bMust start with one of the given values
ends_with:a,bMust end with one of the given values
doesnt_start_with:a,bMust not start with any of the given values
doesnt_end_with:a,bMust not end with any of the given values
regex:patternMust match the regex pattern
not_regex:patternMust not match the regex pattern
same:fieldMust match another field's value
different:fieldMust differ from another field's value
confirmedMust have a matching {field}_confirmation field

Note: Regex patterns cannot contain | (the rule separator). Use Extend() for complex patterns.

Numeric

RuleDescription
integerMust be an integer
numericMust be numeric (int or float)
decimal:min,maxMust have between min and max decimal places
digits:nExactly n digits
digits_between:min,maxBetween min and max digits
multiple_of:nMust be a multiple of n
min:nMinimum value (numeric) or minimum length (string/array)
max:nMaximum value (numeric) or maximum length (string/array)
between:min,maxBetween min and max (numeric or string length)
size:nExact size — character count for strings, item count for arrays, numeric value
gt:n or gt:fieldGreater than value or another field
gte:n or gte:fieldGreater than or equal
lt:n or lt:fieldLess than value or another field
lte:n or lte:fieldLess than or equal

Boolean

RuleDescription
booleanMust be a boolean-like value (true, false, 1, 0, "1", "0")
acceptedMust be an accepted value (yes, on, 1, true)
declinedMust be a declined value (no, off, 0, false)
accepted_if:field,valueMust be accepted when another field equals a value
declined_if:field,valueMust be declined when another field equals a value

Dates

Supported date layouts: 2006-01-02, 02/01/2006, 01/02/2006, 2006-01-02 15:04:05, 2006-01-02T15:04:05Z07:00.

RuleDescription
dateValid date string
date_format:layoutMatches the given Go time layout
date_equals:dateEquals the given date
before:dateMust be before the given date
before_or_equal:dateMust be before or equal to the given date
after:dateMust be after the given date
after_or_equal:dateMust be after or equal to the given date
timezoneValid IANA timezone name (e.g. Asia/Kuala_Lumpur)

Network

RuleDescription
ipValid IPv4 or IPv6 address
ipv4Valid IPv4 address
ipv6Valid IPv6 address
mac_addressValid MAC address (colon or hyphen separated)

Arrays

RuleDescription
arrayMust be a []any
distinctArray items must be unique
in:a,b,cValue must be one of the listed values
not_in:a,b,cValue must not be one of the listed values

Database

Requires .WithDB(db). Returns a db_required error if no DB is attached.

RuleDescription
unique:table,columnValue must not exist in the given column
unique:table,column,ignoreValue,ignoreColumnUnique but ignore a specific row (for updates)
exists:table,columnValue must exist in the given column
// On create"email": "required|email|unique:users,email"// On update — ignore the current user's row"email": "required|email|unique:users,email,42,id"

ignoreColumn defaults to id if omitted.

Custom messages

Override any message globally with field.rule keys, or just rule for field-agnostic overrides.

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Please provide your email.",
"email.email": "That email address is not valid.",
"password.min": "Password needs at least :param characters.",
})

Available placeholders: :field, :param, :other, :value, :min, :max.

Typed rule builder

R() returns a *RuleBuilder. Chain methods, then call Build() to produce the pipe-separated string. Both styles are fully compatible with Make().

validator.Rules{
// string style"email": "required|email|max:100",
// typed builder — compile-safe, IDE autocomplete"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
"slug": validator.R().Required().Regex(`^[a-z0-9-]+$`).Build(),
"score": validator.R().Required().Numeric().Between(0, 100).Build(),
}

Every built-in rule has a corresponding method. A few naming notes:

Rule stringBuilder method
string.Str() (reserved word in Go)
required_if:field,val.RequiredIf("field", "val")
starts_with:a,b.StartsWith("a", "b")
in:a,b,c.In("a", "b", "c")
unique:users,email.Unique("users", "email")

Nested validation

Use dot notation to validate fields inside nested maps:

// Input
{
"user": {
"name": "hamizi",
"address": {
"postcode": "50000"
}
}
}
// Rulesvalidator.Make(input, validator.Rules{
"user.name": "required|min:3",
"user.address.postcode": "required|digits:5",
})

Array wildcard

Use field.* to validate every element of an array. Errors are keyed as field.0, field.1, etc.

// Input
{
"tags": ["laravel", "golang", ""]
}
// Rulesvalidator.Make(input, validator.Rules{
"tags": "required|array",
"tags.*": "required|string|min:2",
})
// Errors// tags.2 → ["The tags.2 field is required."]

Custom rules

Register reusable rules with Extend:

validator.Extend("strong_password", func(fieldstring, valueany, paramstring) error {
s, ok:=value.(string)
if!ok||len(s) <12 {
returnfmt.Errorf("The %s must be at least 12 characters.", field)
}
returnnil
})
// Use it like any built-in rulevalidator.Make(input, validator.Rules{
"password": "required|strong_password",
})

Usage with Fiber

funcCreateUser(c*fiber.Ctx) error {
varbodymap[string]anyiferr:=c.BodyParser(&body); err!=nil {
returnc.Status(400).JSON(fiber.Map{"error": "invalid body"})
}
v:=validator.Make(validator.Input(body), validator.Rules{
"name": "required|string|min:2|max:100",
"email": "required|email|unique:users,email",
"password": "required|min:8|confirmed",
"role": "required|in:admin,user,editor",
}).WithDB(db)
ifv.Fails() {
returnc.Status(422).JSON(v.Errors())
}
// proceed with validated input ...returnc.SendStatus(201)
}

Testing

# Run all tests
go test ./tests/...
# Verbose
go test ./tests/... -v

License

Distributed under MIT License, please see license file within the code for more details.

About

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - hymns/go-validator: A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings. · GitHub
Skip to content

Repository files navigation

go-validator

GitHub release (latest SemVer)Go VersionGo Report CardGoDocMIT License

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings or use the fluent typed builder.

Installation

go get github.com/hymns/go-validator

Quick start

import validator "github.com/hymns/go-validator"v:=validator.Make(
validator.Input{
"email": "user@example.com",
"password": "secret",
"age": "17",
},
validator.Rules{
"email": "required|email",
"password": "required|min:8",
"age": "required|integer|min:18",
},
)
ifv.Fails() {
fmt.Println(v.Errors()) // map[age:["The age must be at least 18."] password:["The password must be at least 8 characters."]]
}

Or use the typed rule builder for compile-time safety and IDE autocompletion:

v:=validator.Make(input, validator.Rules{
"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
})

API

Make(input, rules) *Validator

Creates a validator. Validation is lazy — it runs on the first call to Fails(), Passes(), or Errors().

(*Validator).Messages(msgs) *Validator

Override error messages. Call before Fails() / Passes().

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Email address is mandatory.",
"email.email": "That doesn't look like a valid email.",
})

(*Validator).Bail() *Validator

Stop validation after the first field that produces an error (global bail). Useful when later fields depend on earlier ones passing.

v:=validator.Make(input, rules).Bail()

For per-field bail (stop checking remaining rules on that field on first failure), add bail to the rule string:

validator.Rules{
"email": "bail|required|email|unique:users,email",
// ↑ stops checking email rules on first failure
}

(*Validator).WithDB(db *sql.DB) *Validator

Attach a database connection for unique and exists rules.

(*Validator).Fails() bool

Returns true if validation failed.

(*Validator).Passes() bool

Returns true if validation passed.

(*Validator).Errors() ErrorBag

Returns all errors. ErrorBag is map[string][]string.

errs:=v.Errors()
errs.Has("email") // boolerrs.First("email") // string — first error message for the field

Rules

Rules are pipe-separated strings. Parameters are colon-separated from the rule name, and multiple parameters are comma-separated.

"required|string|min:3|max:100"
"required|in:admin,user,editor"
"required|unique:users,email"

Presence & required

RuleDescription
requiredField must be present and non-empty
nullableField may be nil; skips all other rules when nil
presentKey must exist in input (value may be empty)
filledIf key is present, value must not be empty
bailStop checking remaining rules for this field on first failure

Conditional required

RuleDescription
required_if:field,valueRequired when another field equals a value
required_unless:field,valueRequired unless another field equals a value
required_with:field1,field2Required when any of the listed fields is present
required_without:field1,field2Required when any of the listed fields is absent
required_with_all:field1,field2Required when all listed fields are present
required_without_all:field1,field2Required when all listed fields are absent

Prohibition

RuleDescription
prohibitedField must be absent or empty
prohibited_if:field,valueProhibited when another field equals a value
prohibited_unless:field,valueProhibited unless another field equals a value

Strings

RuleDescription
stringMust be a string
alphaLetters only (Unicode)
alpha_numLetters and numbers only
alpha_dashLetters, numbers, hyphens, and underscores
emailValid email format
urlValid URL (http/https)
active_urlURL with resolvable host
uuidValid UUID (any version)
ulidValid ULID
hex_colorHex color code (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)
jsonValid JSON string
lowercaseAll lowercase
uppercaseAll uppercase
starts_with:a,bMust start with one of the given values
ends_with:a,bMust end with one of the given values
doesnt_start_with:a,bMust not start with any of the given values
doesnt_end_with:a,bMust not end with any of the given values
regex:patternMust match the regex pattern
not_regex:patternMust not match the regex pattern
same:fieldMust match another field's value
different:fieldMust differ from another field's value
confirmedMust have a matching {field}_confirmation field

Note: Regex patterns cannot contain | (the rule separator). Use Extend() for complex patterns.

Numeric

RuleDescription
integerMust be an integer
numericMust be numeric (int or float)
decimal:min,maxMust have between min and max decimal places
digits:nExactly n digits
digits_between:min,maxBetween min and max digits
multiple_of:nMust be a multiple of n
min:nMinimum value (numeric) or minimum length (string/array)
max:nMaximum value (numeric) or maximum length (string/array)
between:min,maxBetween min and max (numeric or string length)
size:nExact size — character count for strings, item count for arrays, numeric value
gt:n or gt:fieldGreater than value or another field
gte:n or gte:fieldGreater than or equal
lt:n or lt:fieldLess than value or another field
lte:n or lte:fieldLess than or equal

Boolean

RuleDescription
booleanMust be a boolean-like value (true, false, 1, 0, "1", "0")
acceptedMust be an accepted value (yes, on, 1, true)
declinedMust be a declined value (no, off, 0, false)
accepted_if:field,valueMust be accepted when another field equals a value
declined_if:field,valueMust be declined when another field equals a value

Dates

Supported date layouts: 2006-01-02, 02/01/2006, 01/02/2006, 2006-01-02 15:04:05, 2006-01-02T15:04:05Z07:00.

RuleDescription
dateValid date string
date_format:layoutMatches the given Go time layout
date_equals:dateEquals the given date
before:dateMust be before the given date
before_or_equal:dateMust be before or equal to the given date
after:dateMust be after the given date
after_or_equal:dateMust be after or equal to the given date
timezoneValid IANA timezone name (e.g. Asia/Kuala_Lumpur)

Network

RuleDescription
ipValid IPv4 or IPv6 address
ipv4Valid IPv4 address
ipv6Valid IPv6 address
mac_addressValid MAC address (colon or hyphen separated)

Arrays

RuleDescription
arrayMust be a []any
distinctArray items must be unique
in:a,b,cValue must be one of the listed values
not_in:a,b,cValue must not be one of the listed values

Database

Requires .WithDB(db). Returns a db_required error if no DB is attached.

RuleDescription
unique:table,columnValue must not exist in the given column
unique:table,column,ignoreValue,ignoreColumnUnique but ignore a specific row (for updates)
exists:table,columnValue must exist in the given column
// On create"email": "required|email|unique:users,email"// On update — ignore the current user's row"email": "required|email|unique:users,email,42,id"

ignoreColumn defaults to id if omitted.

Custom messages

Override any message globally with field.rule keys, or just rule for field-agnostic overrides.

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Please provide your email.",
"email.email": "That email address is not valid.",
"password.min": "Password needs at least :param characters.",
})

Available placeholders: :field, :param, :other, :value, :min, :max.

Typed rule builder

R() returns a *RuleBuilder. Chain methods, then call Build() to produce the pipe-separated string. Both styles are fully compatible with Make().

validator.Rules{
// string style"email": "required|email|max:100",
// typed builder — compile-safe, IDE autocomplete"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
"slug": validator.R().Required().Regex(`^[a-z0-9-]+$`).Build(),
"score": validator.R().Required().Numeric().Between(0, 100).Build(),
}

Every built-in rule has a corresponding method. A few naming notes:

Rule stringBuilder method
string.Str() (reserved word in Go)
required_if:field,val.RequiredIf("field", "val")
starts_with:a,b.StartsWith("a", "b")
in:a,b,c.In("a", "b", "c")
unique:users,email.Unique("users", "email")

Nested validation

Use dot notation to validate fields inside nested maps:

// Input
{
"user": {
"name": "hamizi",
"address": {
"postcode": "50000"
}
}
}
// Rulesvalidator.Make(input, validator.Rules{
"user.name": "required|min:3",
"user.address.postcode": "required|digits:5",
})

Array wildcard

Use field.* to validate every element of an array. Errors are keyed as field.0, field.1, etc.

// Input
{
"tags": ["laravel", "golang", ""]
}
// Rulesvalidator.Make(input, validator.Rules{
"tags": "required|array",
"tags.*": "required|string|min:2",
})
// Errors// tags.2 → ["The tags.2 field is required."]

Custom rules

Register reusable rules with Extend:

validator.Extend("strong_password", func(fieldstring, valueany, paramstring) error {
s, ok:=value.(string)
if!ok||len(s) <12 {
returnfmt.Errorf("The %s must be at least 12 characters.", field)
}
returnnil
})
// Use it like any built-in rulevalidator.Make(input, validator.Rules{
"password": "required|strong_password",
})

Usage with Fiber

funcCreateUser(c*fiber.Ctx) error {
varbodymap[string]anyiferr:=c.BodyParser(&body); err!=nil {
returnc.Status(400).JSON(fiber.Map{"error": "invalid body"})
}
v:=validator.Make(validator.Input(body), validator.Rules{
"name": "required|string|min:2|max:100",
"email": "required|email|unique:users,email",
"password": "required|min:8|confirmed",
"role": "required|in:admin,user,editor",
}).WithDB(db)
ifv.Fails() {
returnc.Status(422).JSON(v.Errors())
}
// proceed with validated input ...returnc.SendStatus(201)
}

Testing

# Run all tests
go test ./tests/...
# Verbose
go test ./tests/... -v

License

Distributed under MIT License, please see license file within the code for more details.

About

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - hymns/go-validator: A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings. · GitHub
Skip to content

Repository files navigation

go-validator

GitHub release (latest SemVer)Go VersionGo Report CardGoDocMIT License

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings or use the fluent typed builder.

Installation

go get github.com/hymns/go-validator

Quick start

import validator "github.com/hymns/go-validator"v:=validator.Make(
validator.Input{
"email": "user@example.com",
"password": "secret",
"age": "17",
},
validator.Rules{
"email": "required|email",
"password": "required|min:8",
"age": "required|integer|min:18",
},
)
ifv.Fails() {
fmt.Println(v.Errors()) // map[age:["The age must be at least 18."] password:["The password must be at least 8 characters."]]
}

Or use the typed rule builder for compile-time safety and IDE autocompletion:

v:=validator.Make(input, validator.Rules{
"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
})

API

Make(input, rules) *Validator

Creates a validator. Validation is lazy — it runs on the first call to Fails(), Passes(), or Errors().

(*Validator).Messages(msgs) *Validator

Override error messages. Call before Fails() / Passes().

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Email address is mandatory.",
"email.email": "That doesn't look like a valid email.",
})

(*Validator).Bail() *Validator

Stop validation after the first field that produces an error (global bail). Useful when later fields depend on earlier ones passing.

v:=validator.Make(input, rules).Bail()

For per-field bail (stop checking remaining rules on that field on first failure), add bail to the rule string:

validator.Rules{
"email": "bail|required|email|unique:users,email",
// ↑ stops checking email rules on first failure
}

(*Validator).WithDB(db *sql.DB) *Validator

Attach a database connection for unique and exists rules.

(*Validator).Fails() bool

Returns true if validation failed.

(*Validator).Passes() bool

Returns true if validation passed.

(*Validator).Errors() ErrorBag

Returns all errors. ErrorBag is map[string][]string.

errs:=v.Errors()
errs.Has("email") // boolerrs.First("email") // string — first error message for the field

Rules

Rules are pipe-separated strings. Parameters are colon-separated from the rule name, and multiple parameters are comma-separated.

"required|string|min:3|max:100"
"required|in:admin,user,editor"
"required|unique:users,email"

Presence & required

RuleDescription
requiredField must be present and non-empty
nullableField may be nil; skips all other rules when nil
presentKey must exist in input (value may be empty)
filledIf key is present, value must not be empty
bailStop checking remaining rules for this field on first failure

Conditional required

RuleDescription
required_if:field,valueRequired when another field equals a value
required_unless:field,valueRequired unless another field equals a value
required_with:field1,field2Required when any of the listed fields is present
required_without:field1,field2Required when any of the listed fields is absent
required_with_all:field1,field2Required when all listed fields are present
required_without_all:field1,field2Required when all listed fields are absent

Prohibition

RuleDescription
prohibitedField must be absent or empty
prohibited_if:field,valueProhibited when another field equals a value
prohibited_unless:field,valueProhibited unless another field equals a value

Strings

RuleDescription
stringMust be a string
alphaLetters only (Unicode)
alpha_numLetters and numbers only
alpha_dashLetters, numbers, hyphens, and underscores
emailValid email format
urlValid URL (http/https)
active_urlURL with resolvable host
uuidValid UUID (any version)
ulidValid ULID
hex_colorHex color code (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)
jsonValid JSON string
lowercaseAll lowercase
uppercaseAll uppercase
starts_with:a,bMust start with one of the given values
ends_with:a,bMust end with one of the given values
doesnt_start_with:a,bMust not start with any of the given values
doesnt_end_with:a,bMust not end with any of the given values
regex:patternMust match the regex pattern
not_regex:patternMust not match the regex pattern
same:fieldMust match another field's value
different:fieldMust differ from another field's value
confirmedMust have a matching {field}_confirmation field

Note: Regex patterns cannot contain | (the rule separator). Use Extend() for complex patterns.

Numeric

RuleDescription
integerMust be an integer
numericMust be numeric (int or float)
decimal:min,maxMust have between min and max decimal places
digits:nExactly n digits
digits_between:min,maxBetween min and max digits
multiple_of:nMust be a multiple of n
min:nMinimum value (numeric) or minimum length (string/array)
max:nMaximum value (numeric) or maximum length (string/array)
between:min,maxBetween min and max (numeric or string length)
size:nExact size — character count for strings, item count for arrays, numeric value
gt:n or gt:fieldGreater than value or another field
gte:n or gte:fieldGreater than or equal
lt:n or lt:fieldLess than value or another field
lte:n or lte:fieldLess than or equal

Boolean

RuleDescription
booleanMust be a boolean-like value (true, false, 1, 0, "1", "0")
acceptedMust be an accepted value (yes, on, 1, true)
declinedMust be a declined value (no, off, 0, false)
accepted_if:field,valueMust be accepted when another field equals a value
declined_if:field,valueMust be declined when another field equals a value

Dates

Supported date layouts: 2006-01-02, 02/01/2006, 01/02/2006, 2006-01-02 15:04:05, 2006-01-02T15:04:05Z07:00.

RuleDescription
dateValid date string
date_format:layoutMatches the given Go time layout
date_equals:dateEquals the given date
before:dateMust be before the given date
before_or_equal:dateMust be before or equal to the given date
after:dateMust be after the given date
after_or_equal:dateMust be after or equal to the given date
timezoneValid IANA timezone name (e.g. Asia/Kuala_Lumpur)

Network

RuleDescription
ipValid IPv4 or IPv6 address
ipv4Valid IPv4 address
ipv6Valid IPv6 address
mac_addressValid MAC address (colon or hyphen separated)

Arrays

RuleDescription
arrayMust be a []any
distinctArray items must be unique
in:a,b,cValue must be one of the listed values
not_in:a,b,cValue must not be one of the listed values

Database

Requires .WithDB(db). Returns a db_required error if no DB is attached.

RuleDescription
unique:table,columnValue must not exist in the given column
unique:table,column,ignoreValue,ignoreColumnUnique but ignore a specific row (for updates)
exists:table,columnValue must exist in the given column
// On create"email": "required|email|unique:users,email"// On update — ignore the current user's row"email": "required|email|unique:users,email,42,id"

ignoreColumn defaults to id if omitted.

Custom messages

Override any message globally with field.rule keys, or just rule for field-agnostic overrides.

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Please provide your email.",
"email.email": "That email address is not valid.",
"password.min": "Password needs at least :param characters.",
})

Available placeholders: :field, :param, :other, :value, :min, :max.

Typed rule builder

R() returns a *RuleBuilder. Chain methods, then call Build() to produce the pipe-separated string. Both styles are fully compatible with Make().

validator.Rules{
// string style"email": "required|email|max:100",
// typed builder — compile-safe, IDE autocomplete"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
"slug": validator.R().Required().Regex(`^[a-z0-9-]+$`).Build(),
"score": validator.R().Required().Numeric().Between(0, 100).Build(),
}

Every built-in rule has a corresponding method. A few naming notes:

Rule stringBuilder method
string.Str() (reserved word in Go)
required_if:field,val.RequiredIf("field", "val")
starts_with:a,b.StartsWith("a", "b")
in:a,b,c.In("a", "b", "c")
unique:users,email.Unique("users", "email")

Nested validation

Use dot notation to validate fields inside nested maps:

// Input
{
"user": {
"name": "hamizi",
"address": {
"postcode": "50000"
}
}
}
// Rulesvalidator.Make(input, validator.Rules{
"user.name": "required|min:3",
"user.address.postcode": "required|digits:5",
})

Array wildcard

Use field.* to validate every element of an array. Errors are keyed as field.0, field.1, etc.

// Input
{
"tags": ["laravel", "golang", ""]
}
// Rulesvalidator.Make(input, validator.Rules{
"tags": "required|array",
"tags.*": "required|string|min:2",
})
// Errors// tags.2 → ["The tags.2 field is required."]

Custom rules

Register reusable rules with Extend:

validator.Extend("strong_password", func(fieldstring, valueany, paramstring) error {
s, ok:=value.(string)
if!ok||len(s) <12 {
returnfmt.Errorf("The %s must be at least 12 characters.", field)
}
returnnil
})
// Use it like any built-in rulevalidator.Make(input, validator.Rules{
"password": "required|strong_password",
})

Usage with Fiber

funcCreateUser(c*fiber.Ctx) error {
varbodymap[string]anyiferr:=c.BodyParser(&body); err!=nil {
returnc.Status(400).JSON(fiber.Map{"error": "invalid body"})
}
v:=validator.Make(validator.Input(body), validator.Rules{
"name": "required|string|min:2|max:100",
"email": "required|email|unique:users,email",
"password": "required|min:8|confirmed",
"role": "required|in:admin,user,editor",
}).WithDB(db)
ifv.Fails() {
returnc.Status(422).JSON(v.Errors())
}
// proceed with validated input ...returnc.SendStatus(201)
}

Testing

# Run all tests
go test ./tests/...
# Verbose
go test ./tests/... -v

License

Distributed under MIT License, please see license file within the code for more details.

About

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - hymns/go-validator: A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings. · GitHub
Skip to content

Repository files navigation

go-validator

GitHub release (latest SemVer)Go VersionGo Report CardGoDocMIT License

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings or use the fluent typed builder.

Installation

go get github.com/hymns/go-validator

Quick start

import validator "github.com/hymns/go-validator"v:=validator.Make(
validator.Input{
"email": "user@example.com",
"password": "secret",
"age": "17",
},
validator.Rules{
"email": "required|email",
"password": "required|min:8",
"age": "required|integer|min:18",
},
)
ifv.Fails() {
fmt.Println(v.Errors()) // map[age:["The age must be at least 18."] password:["The password must be at least 8 characters."]]
}

Or use the typed rule builder for compile-time safety and IDE autocompletion:

v:=validator.Make(input, validator.Rules{
"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
})

API

Make(input, rules) *Validator

Creates a validator. Validation is lazy — it runs on the first call to Fails(), Passes(), or Errors().

(*Validator).Messages(msgs) *Validator

Override error messages. Call before Fails() / Passes().

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Email address is mandatory.",
"email.email": "That doesn't look like a valid email.",
})

(*Validator).Bail() *Validator

Stop validation after the first field that produces an error (global bail). Useful when later fields depend on earlier ones passing.

v:=validator.Make(input, rules).Bail()

For per-field bail (stop checking remaining rules on that field on first failure), add bail to the rule string:

validator.Rules{
"email": "bail|required|email|unique:users,email",
// ↑ stops checking email rules on first failure
}

(*Validator).WithDB(db *sql.DB) *Validator

Attach a database connection for unique and exists rules.

(*Validator).Fails() bool

Returns true if validation failed.

(*Validator).Passes() bool

Returns true if validation passed.

(*Validator).Errors() ErrorBag

Returns all errors. ErrorBag is map[string][]string.

errs:=v.Errors()
errs.Has("email") // boolerrs.First("email") // string — first error message for the field

Rules

Rules are pipe-separated strings. Parameters are colon-separated from the rule name, and multiple parameters are comma-separated.

"required|string|min:3|max:100"
"required|in:admin,user,editor"
"required|unique:users,email"

Presence & required

RuleDescription
requiredField must be present and non-empty
nullableField may be nil; skips all other rules when nil
presentKey must exist in input (value may be empty)
filledIf key is present, value must not be empty
bailStop checking remaining rules for this field on first failure

Conditional required

RuleDescription
required_if:field,valueRequired when another field equals a value
required_unless:field,valueRequired unless another field equals a value
required_with:field1,field2Required when any of the listed fields is present
required_without:field1,field2Required when any of the listed fields is absent
required_with_all:field1,field2Required when all listed fields are present
required_without_all:field1,field2Required when all listed fields are absent

Prohibition

RuleDescription
prohibitedField must be absent or empty
prohibited_if:field,valueProhibited when another field equals a value
prohibited_unless:field,valueProhibited unless another field equals a value

Strings

RuleDescription
stringMust be a string
alphaLetters only (Unicode)
alpha_numLetters and numbers only
alpha_dashLetters, numbers, hyphens, and underscores
emailValid email format
urlValid URL (http/https)
active_urlURL with resolvable host
uuidValid UUID (any version)
ulidValid ULID
hex_colorHex color code (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)
jsonValid JSON string
lowercaseAll lowercase
uppercaseAll uppercase
starts_with:a,bMust start with one of the given values
ends_with:a,bMust end with one of the given values
doesnt_start_with:a,bMust not start with any of the given values
doesnt_end_with:a,bMust not end with any of the given values
regex:patternMust match the regex pattern
not_regex:patternMust not match the regex pattern
same:fieldMust match another field's value
different:fieldMust differ from another field's value
confirmedMust have a matching {field}_confirmation field

Note: Regex patterns cannot contain | (the rule separator). Use Extend() for complex patterns.

Numeric

RuleDescription
integerMust be an integer
numericMust be numeric (int or float)
decimal:min,maxMust have between min and max decimal places
digits:nExactly n digits
digits_between:min,maxBetween min and max digits
multiple_of:nMust be a multiple of n
min:nMinimum value (numeric) or minimum length (string/array)
max:nMaximum value (numeric) or maximum length (string/array)
between:min,maxBetween min and max (numeric or string length)
size:nExact size — character count for strings, item count for arrays, numeric value
gt:n or gt:fieldGreater than value or another field
gte:n or gte:fieldGreater than or equal
lt:n or lt:fieldLess than value or another field
lte:n or lte:fieldLess than or equal

Boolean

RuleDescription
booleanMust be a boolean-like value (true, false, 1, 0, "1", "0")
acceptedMust be an accepted value (yes, on, 1, true)
declinedMust be a declined value (no, off, 0, false)
accepted_if:field,valueMust be accepted when another field equals a value
declined_if:field,valueMust be declined when another field equals a value

Dates

Supported date layouts: 2006-01-02, 02/01/2006, 01/02/2006, 2006-01-02 15:04:05, 2006-01-02T15:04:05Z07:00.

RuleDescription
dateValid date string
date_format:layoutMatches the given Go time layout
date_equals:dateEquals the given date
before:dateMust be before the given date
before_or_equal:dateMust be before or equal to the given date
after:dateMust be after the given date
after_or_equal:dateMust be after or equal to the given date
timezoneValid IANA timezone name (e.g. Asia/Kuala_Lumpur)

Network

RuleDescription
ipValid IPv4 or IPv6 address
ipv4Valid IPv4 address
ipv6Valid IPv6 address
mac_addressValid MAC address (colon or hyphen separated)

Arrays

RuleDescription
arrayMust be a []any
distinctArray items must be unique
in:a,b,cValue must be one of the listed values
not_in:a,b,cValue must not be one of the listed values

Database

Requires .WithDB(db). Returns a db_required error if no DB is attached.

RuleDescription
unique:table,columnValue must not exist in the given column
unique:table,column,ignoreValue,ignoreColumnUnique but ignore a specific row (for updates)
exists:table,columnValue must exist in the given column
// On create"email": "required|email|unique:users,email"// On update — ignore the current user's row"email": "required|email|unique:users,email,42,id"

ignoreColumn defaults to id if omitted.

Custom messages

Override any message globally with field.rule keys, or just rule for field-agnostic overrides.

v:=validator.Make(input, rules).Messages(validator.Messages{
"email.required": "Please provide your email.",
"email.email": "That email address is not valid.",
"password.min": "Password needs at least :param characters.",
})

Available placeholders: :field, :param, :other, :value, :min, :max.

Typed rule builder

R() returns a *RuleBuilder. Chain methods, then call Build() to produce the pipe-separated string. Both styles are fully compatible with Make().

validator.Rules{
// string style"email": "required|email|max:100",
// typed builder — compile-safe, IDE autocomplete"email": validator.R().Required().Email().Max(100).Build(),
"age": validator.R().Required().Integer().Min(18).Build(),
"role": validator.R().Required().In("admin", "user").Build(),
"slug": validator.R().Required().Regex(`^[a-z0-9-]+$`).Build(),
"score": validator.R().Required().Numeric().Between(0, 100).Build(),
}

Every built-in rule has a corresponding method. A few naming notes:

Rule stringBuilder method
string.Str() (reserved word in Go)
required_if:field,val.RequiredIf("field", "val")
starts_with:a,b.StartsWith("a", "b")
in:a,b,c.In("a", "b", "c")
unique:users,email.Unique("users", "email")

Nested validation

Use dot notation to validate fields inside nested maps:

// Input
{
"user": {
"name": "hamizi",
"address": {
"postcode": "50000"
}
}
}
// Rulesvalidator.Make(input, validator.Rules{
"user.name": "required|min:3",
"user.address.postcode": "required|digits:5",
})

Array wildcard

Use field.* to validate every element of an array. Errors are keyed as field.0, field.1, etc.

// Input
{
"tags": ["laravel", "golang", ""]
}
// Rulesvalidator.Make(input, validator.Rules{
"tags": "required|array",
"tags.*": "required|string|min:2",
})
// Errors// tags.2 → ["The tags.2 field is required."]

Custom rules

Register reusable rules with Extend:

validator.Extend("strong_password", func(fieldstring, valueany, paramstring) error {
s, ok:=value.(string)
if!ok||len(s) <12 {
returnfmt.Errorf("The %s must be at least 12 characters.", field)
}
returnnil
})
// Use it like any built-in rulevalidator.Make(input, validator.Rules{
"password": "required|strong_password",
})

Usage with Fiber

funcCreateUser(c*fiber.Ctx) error {
varbodymap[string]anyiferr:=c.BodyParser(&body); err!=nil {
returnc.Status(400).JSON(fiber.Map{"error": "invalid body"})
}
v:=validator.Make(validator.Input(body), validator.Rules{
"name": "required|string|min:2|max:100",
"email": "required|email|unique:users,email",
"password": "required|min:8|confirmed",
"role": "required|in:admin,user,editor",
}).WithDB(db)
ifv.Fails() {
returnc.Status(422).JSON(v.Errors())
}
// proceed with validated input ...returnc.SendStatus(201)
}

Testing

# Run all tests
go test ./tests/...
# Verbose
go test ./tests/... -v

License

Distributed under MIT License, please see license file within the code for more details.

About

A Laravel-inspired validation package for Go. No struct tags required — pass your data as a plain map and declare rules as pipe-separated strings.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages