We can treat a given variable as a complete parameter for validation, i.e., single data validation. If a variable is a complex type like Struct/Map
, and we need to validate its internal attributes/key-value pairs, this scenario will be introduced in later chapters. Single data validation must specify the data to be validated through the Data
method and the validation rules through the Rule
method. Single data validation is relatively straightforward. Let’s look at some examples.
Validate Data Length With Default Error Messages
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
ctx = gctx.New()
rule = "length:6,16"
)
if err := g.Validator().Rules(rule).Data("123456").Run(ctx); err != nil {
fmt.Println(err.String())
}
if err := g.Validator().Rules(rule).Data("12345").Run(ctx); err != nil {
fmt.Println(err.String())
}
}
After execution, the terminal output:
The value `12345` length must be between 6 and 16
Validate Data Type and Size With Custom Error Messages
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
ctx = gctx.New()
rule = "integer|between:6,16"
messages = "Please enter an integer|The parameter size is incorrect, my friend"
value = 5.66
)
if err := g.Validator().Rules(rule).Messages(messages).Data(value).Run(ctx); err != nil {
g.Dump(err.Map())
}
}
After execution, the terminal output:
{
"integer": "Please enter an integer",
"between": "The parameter size is incorrect, my friend",
}
As you can see, multiple rules and multiple custom error messages are separated using the |
character in English. Note that the order of custom error messages corresponds one-to-one with the order of multiple rules. The messages
parameter supports not only string
types but also map[string]string
types, as shown in the following example:
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
ctx = gctx.New()
rule = "url|min-length:11"
value = "goframe.org"
messages = map[string]string{
"url": "Please enter a valid URL address",
"min-length": "The address must be at least {min} characters long",
}
)
if err := g.Validator().Rules(rule).Messages(messages).Data(value).Run(ctx); err != nil {
g.Dump(err.Map())
}
}
After execution, the terminal output:
{
"url": "Please enter a valid URL address",
}
Use Custom Regex to Validate Data Format With Default Error Messages
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
ctx = gctx.New()
rule = `regex:\d{6,}|\D{6,}|max-length:16`
)
if err := g.Validator().Rules(rule).Data(`123456`).Run(ctx); err != nil {
fmt.Println(err)
}
if err := g.Validator().Rules(rule).Data(`abcde6`).Run(ctx); err != nil {
fmt.Println(err)
}
}
After execution, the terminal output:
The value `abcde6` must be in regex of: \d{6,}|\D{6,}