Игорь Лазарев техлид istock.info https://t.me/strider2038
type Document struct {
Title string `valid:"required"`
Keyword string `valid:"stringlength(5|10)"`
Tags []string // нет встроенной проверки на длину слайса
}
func main() {
document := Document{
Title: "",
Keyword: "book",
}
result, err := govalidator.ValidateStruct(document)
if err != nil {
fmt.Println("error: " + err.Error())
}
}
document := Document{
Title: "",
Keywords: []string{"", "book", "fantasy", "book"},
}
err := validation.ValidateStruct(&document,
validation.Field(&document.Title, validation.Required),
validation.Field(&document.Keywords, validation.Required, validation.Length(5, 10)),
)
var errs validation.Errors // map[string]error
if errors.As(err, &errs) {
for field, e := range errs {
fmt.Println(field+":", e.Error())
}
}
interace{} => runtime errors;interface{}Особенности библиотеки
time.Timeimport (
"context"
"fmt"
"github.com/muonsoft/validation"
"github.com/muonsoft/validation/it"
)
func main() {
validator, _ := validation.NewValidator()
err := validator.Validate(context.Background(),
// список опций-аргументов
validation.String("", // валидируемое значение // HL
// далее список правил
it.IsNotBlank(), // HL
it.HasMaxLength(100), // HL
),
)
fmt.Println(err)
// Output:
// violation: This value should not be blank.
}
document := Document{
Title: "", // HL00
Keywords: []string{"", "book", "fantasy", "book"}, // HL00
}
err := validator.Validate(context.Background(),
validation.StringProperty("title", document.Title, it.IsNotBlank()), // HL01
validation.CountableProperty("keywords", len(document.Keywords), it.HasCountBetween(5, 10)), // HL02
validation.ComparablesProperty[string]("keywords", document.Keywords, it.HasUniqueValues[string]()), // HL03
validation.EachStringProperty("keywords", document.Keywords, it.IsNotBlank()), // HL04
)
if violations, ok := validation.UnwrapViolationList(err); ok { // HL05
violations.ForEach(func(i int, violation validation.Violation) error { // HL05
fmt.Println(violation)
return nil
})
}
// Output:
// violation at 'title': This value should not be blank.
// violation at 'keywords': This collection should contain 5 elements or more.
// violation at 'keywords': This collection should contain only unique elements.
// violation at 'keywords[0]': This value should not be blank.
validator, _ := validation.NewValidator(validation.Translations(russian.Messages)) // HL01
document := Document{
Title: "",
Keywords: []string{"", "book", "fantasy", "book"},
}
ctx := language.WithContext(context.Background(), language.Russian) // HL01
err := validator.Validate(
ctx,
validation.StringProperty("title", document.Title, it.IsNotBlank()),
validation.AtProperty(
"keywords",
validation.Countable(len(document.Keywords), it.HasCountBetween(5, 10)),
validation.Comparables[string](document.Keywords, it.HasUniqueValues[string]()),
validation.EachString(document.Keywords, it.IsNotBlank()),
),
)
data, _ := json.MarshalIndent(err, "", "\t") // HL02
fmt.Println(string(data))
[
{
"error": "is blank",
"message": "Значение не должно быть пустым.",
"propertyPath": "title"
},
{
"error": "too few elements",
"message": "Эта коллекция должна содержать 5 элементов или больше.",
"propertyPath": "keywords"
},
{
"error": "is not unique",
"message": "Эта коллекция должна содержать только уникальные элементы.",
"propertyPath": "keywords"
},
{
"error": "is blank",
"message": "Значение не должно быть пустым.",
"propertyPath": "keywords[0]"
}
]
type Product struct {
Name string
Tags []string
Components []Component
}
func (p Product) Validate(ctx context.Context, validator *validation.Validator) error { // HL01
return validator.Validate(
ctx,
validation.StringProperty("name", p.Name, it.IsNotBlank()),
validation.AtProperty(
"tags",
validation.Countable(len(p.Tags), it.HasMinCount(5)),
validation.Comparables[string](p.Tags, it.HasUniqueValues[string]()),
validation.EachString(p.Tags, it.IsNotBlank()),
),
validation.AtProperty(
"components",
validation.Countable(len(p.Components), it.HasMinCount(1)),
// this runs validation on each of the components
validation.ValidSlice(p.Components), // HL02
),
)
}
p := Product{
Name: "",
Tags: []string{"device", "", "phone", "device"},
Components: []Component{{ID: 1, Name: ""}},
}
err := validator.ValidateIt(context.Background(), p) // HL03
if violations, ok := validation.UnwrapViolationList(err); ok {
violations.ForEach(func(i int, violation validation.Violation) error {
fmt.Println(violation)
return nil
})
}
// Output:
// violation at 'name': This value should not be blank.
// violation at 'tags': This collection should contain 5 elements or more.
// violation at 'tags': This collection should contain only unique elements.
// violation at 'tags[1]': This value should not be blank.
// violation at 'components[0].name': This value should not be blank.
// violation at 'components[0].tags': This collection should contain 1 element or more.
validation.AtLeastOneOf()validation.Sequentially()validation.All()validation.When()validation.Async()err := validator.Validate(
context.Background(),
validation.AtLeastOneOf(
validation.CountableProperty("keywords", len(banner.Keywords), it.IsNotBlank()),
validation.CountableProperty("companies", len(banner.Companies), it.IsNotBlank()),
validation.CountableProperty("brands", len(banner.Brands), it.IsNotBlank()),
),
)
type User struct {
Email string
Password string
City string
}
func (u User) Validate(ctx context.Context, validator *validation.Validator) error {
return validator.Validate(
ctx,
validation.StringProperty(
"email",
u.Email,
it.IsNotBlank().WhenGroups("registration"), // HL
it.IsEmail().WhenGroups("registration"), // HL
),
validation.StringProperty(
"password",
u.Password,
it.IsNotBlank().WhenGroups("registration"),
it.HasMinLength(7).WhenGroups("registration"),
),
validation.StringProperty(
"city",
u.City,
it.HasMinLength(2), // this constraint belongs to the default group
),
)
}
err1 := validator.WithGroups("registration").Validate( // HL
context.Background(),
validation.Valid(user),
)
err2 := validator.Validate(
context.Background(),
validation.Valid(user),
)
v0.Спасибо за внимание! Буду рад любой обратной связи.