Skip to main content
Version: 2.8.x(Latest)

Optional Validation Rules

When the given data validation rules do not include the required* rule, it indicates that the rule is not a mandatory rule. If the given value is nil or an empty string, its validation will be ignored.

Example 1: Empty String

package main

import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)

func main() {
type Params struct {
Page int `v:"required|min:1 # page is required"`
Size int `v:"required|between:1,100 # size is required"`
ProjectId string `v:"between:1,10000 # project id must between {min}, {max}"`
}
var (
ctx = gctx.New()
obj = &Params{
Page: 1,
Size: 10,
}
)

err := g.Validator().Data(obj).Run(ctx)
fmt.Println(err)

// Output:
// <nil>
}

Example 2: Null Pointer Attribute

package main

import (
"fmt"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)

func main() {
type Params struct {
Page int `v:"required|min:1 # page is required"`
Size int `v:"required|between:1,100 # size is required"`
ProjectId *gvar.Var `v:"between:1,10000 # project id must between {min}, {max}"`
}
var (
ctx = gctx.New()
obj = &Params{
Page: 1,
Size: 10,
}
)
err := g.Validator().Data(obj).Run(ctx)
fmt.Println(err)

// Output:
// <nil>
}

Example 3: Empty Integer Attribute

Note that if the key value is 0 or false, the parameter value will still be validated.

package main

import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)

func main() {
type Params struct {
Page int `v:"required|min:1 # page is required"`
Size int `v:"required|between:1,100 # size is required"`
ProjectId int `v:"between:1,10000 # project id must between {min}, {max}"`
}
var (
ctx = gctx.New()
obj = &Params{
Page: 1,
Size: 10,
}
)
err := g.Validator().Data(obj).Run(ctx)
fmt.Println(err)

// Output:
// <nil>
}

After execution, the terminal outputs:

project id must between 1, 10000

Example 4: Parameter Passing Through map

package main

import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)

func main() {
var (
ctx = gctx.New()
params = map[string]interface{}{
"passport": "",
"password": "123456",
"password2": "1234567",
}
rules = []string{
"passport@length:6,16",
"password@required|length:6,16|same:password2",
"password2@required|length:6,16",
}
)
err := g.Validator().Rules(rules).Data(params).Run(ctx)
if err != nil {
g.Dump(err.Maps())
}
}

Note that the passport key does not have the required rule, so even if the given passport parameter is an empty string and does not meet the rule, it does not trigger an error, since the validation component considers it an optional validation rule.

After execution, the terminal outputs:

{
"password": {
"same": "The password value `123456` must be the same as field password2",
},
}