Skip to content

How to validate struct without struct tag? #853

@chenyanchen

Description

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

Package version v10:

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

Issue, Question or Enhancement:

I made some gRPC services with protobuf, the generated files has no struct tags. How to validate a struct without struct tags?

Maybe gogo/protobuf can add some struct tags into the generation files, but this is no matter to use a new package for the complex method.

I find the same problem #722 not same pain spot and closed.

There is some simply method to solove this problem?

Code sample, to showcase or reproduce:

.proto file

message SearchRequest {
  string RequestID = 1;
  uint64 UserID = 2;
  string Email = 3;
  repeated string Keywords = 4;
}

Generated structure:

type SearchRequest struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	RequestID string   `protobuf:"bytes,1,opt,name=RequestID,proto3" json:"RequestID,omitempty"`
	UserID    uint64   `protobuf:"varint,2,opt,name=UserID,proto3" json:"UserID,omitempty"`
	Email     string   `protobuf:"bytes,3,opt,name=Email,proto3" json:"Email,omitempty"`
	Keywords  []string `protobuf:"bytes,4,rep,name=Keywords,proto3" json:"Keywords,omitempty"`
}

I want validate this structure equal this:

type SearchRequest struct {
	RequestID string `validate:"required"`
	UserID    uint64
	Email     string   `validate:"omitempty,email"`
	Keywords  []string `validate:"dive,required"`
}

In the proto generated files, there is no tags, so I expect a method like RegisterStructMap, the map[string]string is map[FieldName]tag.

func main() {
	v := validator.New()
	v.RegisterStructMap(
		proto.SearchRequest{}, map[string]string{
			"RequestID": "required",
			"Email":     "omitempty,email",
			"Keywords":  "dive,required",
		},
	)
	req := &proto.SearchRequest{
		Keywords: []string{""},
	}
	if err := v.Struct(req); err != nil {
		fmt.Println(err)
	}
}
// Output:
//     Key: 'SearchRequest.RequestID' Error:Field validation for 'RequestID' failed on the 'required' tag
//     Key: 'SearchRequest.Keywords[0]' Error:Field validation for 'Keywords[0]' failed on the 'required' tag

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions