Skip to content

feat: implement ValidatorValuer interface feature #1416

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

thommeo
Copy link

@thommeo thommeo commented Apr 16, 2025

Problem

In order to have custom type validations for generic types, every possible type has to be registered with RegisterCustomTypeFunc to return the underlying type. It is especially relevant for nullable types e.g. sql.Null[T].

Discussed here: #1232

Fixes Or Enhances

  • Adds a mechanism for validating generic types without using RegisterCustomTypeFunc by introducing ValidatorValuer interface.

Example:

type Nullable[T any] struct {
	Data T
}

func (t Nullable[T]) ValidatorValue() any {
	return t.Data
}

type Config struct {
	Name string `validate:"required"`
}

type Record struct {
	Config Nullable[Config] `validate:"required"`
}

func TestValidatorValuerInterface2(t *testing.T) {
	s := Record{
		Config: Nullable[Config]{},
	}
	v := New()
	errs := v.Struct(s)
	t.Fatalf("Error: %v", errs.Error())
}

// Key: 'Record.Config.Name' Error:Field validation for 'Name' failed on the 'required' tag
// Notice: no Data in the Record.Config.Name

Make sure that you've checked the boxes below before you submit PR:

  • Tests exist or have been written that cover this particular change.

@go-playground/validator-maintainers

@thommeo thommeo requested a review from a team as a code owner April 16, 2025 12:54
@coveralls
Copy link

coveralls commented Apr 16, 2025

Coverage Status

coverage: 73.659% (+0.006%) from 73.653%
when pulling a4b2773 on thommeo:feat/validation-valuer
into c3fc72e on go-playground:master.

# Conflicts:
#	validator_test.go
@thommeo thommeo force-pushed the feat/validation-valuer branch from 7222de7 to a4b2773 Compare April 27, 2025 19:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants