+
Skip to content

Scenes does not work in slices #283

@manicar2093

Description

@manicar2093

System (please complete the following information):

  • OS: macOS
  • GO Version: 1.23.3
  • Pkg Version: 1.5.4

Describe the bug

Scenes does not detect slice type

To Reproduce

package main

import (
	"fmt"
	"github.com/gookit/validate"
)

func main() {
	u := &UserForm{
		Name: "inhere",
		Code: "asd",
		Test: 1,
	}

	v := validate.Struct(u, "add")
	v.StopOnError = false
	// v := validate.New(u)

	if v.Validate("add") { // validate ok
		// do something ...
	} else {
		fmt.Println(v.Errors) // all error messages
	}

	fmt.Println()
	fmt.Println()
	fmt.Println()
	fmt.Println()
	fmt.Println()
	fmt.Println()

	v = validate.Struct(u, "update")
	v.StopOnError = false
	// v := validate.New(u)

	if v.Validate("update") { // validate ok
		// do something ...
	} else {
		fmt.Println(v.Errors) // all error messages
	}
}

// UserForm struct
type UserForm struct {
	Name string `validate:"required|min_len:7"`
	Code string `validate:"required|customValidator"`
	// ExtInfo nested struct
	ExtInfo struct {
		Homepage string `validate:"required"`
		CityName string
	} `validate:"required"`
	Tags []struct {
		Id   string `validate:"required"`
		Name string `validate:"required"`
		Date string `validate:"required"`
	} `validate:"required"`
	Test int `validate:"required|greaterThan:1"`
}

// CustomValidator custom validator in the source struct.
func (f UserForm) CustomValidator(val string) bool {
	res := len(val) == 4
	return res
}

// ConfigValidation config the Validation
// eg:
// - define validate scenes
func (f UserForm) ConfigValidation(v *validate.Validation) {
	v.WithScenes(validate.SValues{
		"add":    []string{"ExtInfo.Homepage", "Name", "Code"},
		"update": []string{"ExtInfo.CityName", "Name", "Tags.Id", "Test"},
	})
}

// Messages you can custom validator error messages.
func (f UserForm) Messages() map[string]string {
	return validate.MS{
		"required":      "oh! the {field} is required",
		"email":         "email is invalid",
		"Name.required": "message for special field",
		"Age.int":       "age must int",
		"Age.min":       "age min value is 1",
	}
}

// Translates you can custom field translates.
func (f UserForm) Translates() map[string]string {
	return validate.MS{
		"Name":             "User Name",
		"Email":            "User Email",
		"ExtInfo.Homepage": "Home Page",
	}
}

Expected behavior

When scene update is used Tags.Id from slice should be validated and show in errors but this does not happen. There is no way to declare this in docs

Screenshots

image

Additional context

I don't know but this seems to be more like a feature request than an issue 😃

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载