Skip to content

AddErrorMessage(...) function

The AddErrorMessage function allows to add an error message to a Validation session without executing a field validator. This function takes in two arguments: name, which is the name of the field for which the error message is being added, and message, which is the error message being added to the session.

When an error message is added using this function, the Validation session is marked as invalid, indicating that at least one validation error has occurred.

One use case for the AddErrorMessage function is to add a general error message for the validation of an entity structure. As shown in the example below, if you have an entity structure for an address and need to validate multiple fields within it, such as the city and street, you can use AddErrorMessage to include a general error message for the entire address in case any of the fields fail validation.

type Address struct {
City string
Street string
}
a := Address{"", "1600 Amphitheatre Pkwy"}
val := v.Is(
v.String(a.city, "city").Not().Blank(),
v.String(a.Street, "street").Not().Blank(),
)
if !val.Valid() {
v.AddErrorMessage("address", "The address is wrong!")
out, _ := json.MarshalIndent(val.Error(), "", " ")
fmt.Println(string(out))
}

output:

{
"address": [
"The address is wrong!"
],
"city": [
"City can't be blank"
]
}

It’s worth noting that there may be other use cases for this function as well.