mwitkow / go-proto-validators

Generate message validators from .proto annotations.
Apache License 2.0
1.09k stars 164 forks source link

customize error message by not modifying the pb.go files(auto gened) #28

Closed jinleileiking closed 6 years ago

jinleileiking commented 7 years ago
func (this *InnerMessage) Validate() error {
    if !(this.SomeInteger > 0) {
        return fmt.Errorf("validation error: InnerMessage.SomeInteger must be greater than '0'")
    }
    if !(this.SomeInteger < 100) {
        return fmt.Errorf("validation error: InnerMessage.SomeInteger must be less than '100'")
    }
    if !(this.SomeFloat >= 0) {
        return fmt.Errorf("validation error: InnerMessage.SomeFloat must be greater than or equal to '0'")
    }
    if !(this.SomeFloat <= 1) {
        return fmt.Errorf("validation error: InnerMessage.SomeFloat must be less than or equal to '1'")

I can modify return fmt.Errorf("validation error: InnerMessage.SomeFloat must be less than or equal to '1'") by change the autogened file. But this is low. Any good way?

malyusha commented 6 years ago

@jinleileiking yes, you can customize message of field error by adding option into .proto file:

message CreateUserData {
    string name = 1 [(validator.field) = {length_gt: 0 length_lt: 100 human_error: "User name is required and must be less than 100 chars length!"}];
}

So the final message will be "invalid field $MESSAGE_NAME.$FIELD_NAME: $text". But you can't remove this invalid field... text.

mwitkow commented 6 years ago

@malyusha thanks for helping out here :)

If you want to strip the invalid field : bit, substr the errors in an interceptor or something :)