go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.83k stars 1.32k forks source link

Validating newtype type definitions of slice types #986

Open Southclaws opened 2 years ago

Southclaws commented 2 years ago

Package version eg. v9, v10: v10

Issue, Question or Enhancement:

I'm trying to write a validator that operates on a type definition (newtype) of a slice of some type T. The reason for this is I want to assert some data that depends on a reduction operation of the items within the slice.

Now I could make this alias into a struct that contains a field but that's going to involve changing a metric ton of code that depends on this structure, it's also an API contract so our JSON interface would have to change too.

I want to keep the validation for this type isolated to just this type as the list of items type is used for many other things so it would be arduous to re-implement this validation layer at the container layer (the structs that contain the list).

Code sample, to showcase or reproduce:

https://go.dev/play/p/D9iZePnD-bA

package main

import (
    "fmt"
    "testing"

    "github.com/go-playground/validator/v10"
)

type Cart struct {
    Items ItemList `validate:"dive"`
}

type Item struct {
    Price int
    Name  string
}

type ItemList []*Item

func Test_SliceTypeDefinition(t *testing.T) {
    v := validator.New()

    v.RegisterStructValidation(func(sl validator.StructLevel) {
        fmt.Println("RegisterStructValidation called")
        sl.ReportError("test", "test", "test", "test", "test")
    }, ItemList{})

    value := Cart{
        Items: ItemList{
            {
                Name:  "one",
                Price: 60,
            },
            {
                Name:  "one",
                Price: 50,
            },
        },
    }

    err := v.Struct(value)

    fmt.Println(err)
}