Skip to content

Commit

Permalink
Add an example of how one might localize errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jchadwick-buf committed Dec 12, 2024
1 parent 0757956 commit 611775b
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions validator_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"errors"
"fmt"
"log"
"os"
"text/template"

pb "github.com/bufbuild/protovalidate-go/internal/gen/tests/example/v1"
"google.golang.org/protobuf/reflect/protoregistry"
Expand Down Expand Up @@ -164,3 +166,42 @@ func ExampleValidationError() {
// output: lat double.gte_lte
// -90 999.999
}

func ExampleValidationError_localized() {
validator, err := New()
if err != nil {
log.Fatal(err)
}

type ErrorInfo struct {
FieldName string
RuleValue any
FieldValue any
}

var ruleMessages = map[string]string{
"string.email_empty": "{{.FieldName}}: メールアドレスは空であってはなりません。\n",
"string.pattern": "{{.FieldName}}: 値はパターン「{{.RuleValue}}」一致する必要があります。\n",
"uint64.gt": "{{.FieldName}}: 値は{{.RuleValue}}を超える必要があります。(価値:{{.FieldValue}})\n",
}

loc := &pb.Person{Id: 900}
err = validator.Validate(loc)
var valErr *ValidationError
if ok := errors.As(err, &valErr); ok {
for _, violation := range valErr.Violations {
_ = template.
Must(template.New("").Parse(ruleMessages[violation.Proto.GetConstraintId()])).
Execute(os.Stdout, ErrorInfo{
FieldName: FieldPathString(violation.Proto.GetField()),
RuleValue: violation.RuleValue.Interface(),
FieldValue: violation.FieldValue.Interface(),
})
}
}

// output:
// id: 値は999を超える必要があります。(価値:900)
// email: メールアドレスは空であってはなりません。
// name: 値はパターン「^[[:alpha:]]+( [[:alpha:]]+)*$」一致する必要があります。
}

0 comments on commit 611775b

Please sign in to comment.