Skip to content

Expose baked in validators for use with custom validators #845

Open
@AaronRobson

Description

@AaronRobson
  • I have looked at the documentation here first?
  • I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

Enhancement - to allow custom validators to use the baked in ones as building blocks (

func isUUID(fl FieldLevel) bool {
)

If the isUuid etc. functions started with a capital letter (i.e. IsUuid etc.) they'd be available to users of the library.

Code sample, to showcase or reproduce:

package main

import (
	"strings"

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

type Example struct {
	Value string `json:"value" validate:"required"`
}

// use a single instance of Validate, it caches struct info
var validate *validator.Validate

func main() {
	validate = validator.New()
	validate.RegisterValidation("uuidwithprefix", validateUuidWithPrefix)

	s := Example{Value: "invalid|74a740c3-ef1d-4333-9f28-930ed602590d"}
	err := validate.Struct(s)
	if err != nil {
		fmt.Printf("Err(s):\n%+v\n", err)
	}

	s.String = "expected-prefix|74a740c3-ef1d-4333-9f28-930ed602590d"
	err = validate.Struct(s)
	if err != nil {
		fmt.Printf("Err(s):\n%+v\n", err)
	}
}

func validateUuidWithPrefix(fl validator.FieldLevel) bool {
	parts := string.Split(fl.Field().String(), "|")
 	if len(parts) != 2 {
		return false
	}
	if parts[0] != "expected-prefix" {
		return false
	}
	return validators.isUuid(parts[1])  <- This fails as isUuid is not exposed by the library
}

Modelled after: https://github.com/go-playground/validator/blob/master/_examples/custom-validation/main.go

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions