Skip to content

Commit

Permalink
Update README to include AddErrorMessage explanation
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosforero committed Mar 14, 2023
1 parent 43587aa commit 7075ef4
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ Valgo is used in production by [Statsignal](https://statsignal.dev), but we want
- [`In(...)` function](#in-function)
- [`InRow(...)` function](#inrow-function)
- [`Check(...)` function](#check-function)
- [`AddErrorMessage(...)` function](#adderrormessage-function)
- [Merging two `Validation` sessions with `Validation.Merge( ... )`](#merging-two-validation-sessions-with-validationmerge--)
- [`New()` function](#new-function)
- [Custom error message template](#custom-error-message-template)
Expand Down Expand Up @@ -310,6 +311,48 @@ output:
}
```

## `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.

```go
type Address struct {
City string
Street string
}

a := Address{"", "1600 Amphitheatre Pkwy"}

val := v.
Is(String(a.city, "city").Not().Blank()).
Is(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:
```json
{
"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.

## 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.
Expand Down

0 comments on commit 7075ef4

Please sign in to comment.