Skip to content

Merging two Validation sessions with Validation Merge

Using Merge(...) you can merge two Validation sessions. When two validations are merged, errors with the same value name will be merged. It is useful for reusing validation logic.

The following example merges the Validation session returned by the validatePreStatus function. Since both Validation sessions validate a value with the name status, the error returned will return two error messages, and without duplicate the Not().Blank() error message rule.

type Record struct {
Name string
Status string
}
validatePreStatus := func(status string) *Validation {
regex, _ := regexp.Compile("pre-.+")
return v.
Is(v.String(status, "status").Not().Blank().MatchingTo(regex))
}
r := Record{"Classified", ""}
val := v.Is(
v.String(r.Name, "name").Not().Blank(),
v.String(r.Status, "status").Not().Blank(),
)
val.Merge(validatePreStatus(r.Status))
if !val.Valid() {
out, _ := json.MarshalIndent(val.Error(), "", " ")
fmt.Println(string(out))
}

output:

{
"status": [
"Status can't be blank",
"Status must match to \"pre-.+\""
]
}