https://github.com/sporto/gleam-valid
Validation library for Gleam
https://github.com/sporto/gleam-valid
gleam gleam-lang
Last synced: about 2 months ago
JSON representation
Validation library for Gleam
- Host: GitHub
- URL: https://github.com/sporto/gleam-valid
- Owner: sporto
- License: apache-2.0
- Created: 2020-10-16T01:07:45.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2025-07-10T03:06:33.000Z (3 months ago)
- Last Synced: 2025-08-17T06:09:38.891Z (about 2 months ago)
- Topics: gleam, gleam-lang
- Language: Gleam
- Homepage: https://hexdocs.pm/valid
- Size: 112 KB
- Stars: 42
- Watchers: 3
- Forks: 5
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
- awesome-gleam - valid - [📚](https://hexdocs.pm/valid/) - A composable validation library for Gleam (Packages / Validation)
README
# Valid

A validation library for [Gleam](https://gleam.run/).
API Docs: .
This library follows the principle [Parse don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/).
## API
```gleam
import validfn user_validator(input: InputUser) {
use age <- valid.check(input.age, valid.int_min(13, "Should be at least 13"))
use name <- valid.check(input.name, valid.string_is_not_empty("Missing name"))
use email <- valid.check(input.email, valid.string_is_email("Missing email"))valid.ok(ValidUser(age:, name:, email:))
}let input = InputUser(age: 14, name: "Sam", email: "sam@sample.com")
let result = input
|> valid.validate(user_validator)result ==
Ok(ValidUser(14, "Sam", "sam@sample.com"))
```### Creating a custom validator
A validator is a function that takes an input, and returns a tuple `#(output, errors)`.
E.g.
```gleam
import valid/experimental as validfn is_99(input) {
case input == 99 {
True -> #(input, [])
False -> #(0, ["Not 99"])
}
}fn validator(input) {
use out <- valid.check(input, is_99)
valid.ok(out)
}
```A validator must return a default value. This is so we can collect all the errors for all validators (instead of returning early).
### Using own errors
By using your own errors you can add information to link to the source of the issue. e.g.
```gleam
type Field {
FieldAge
FieldName
FieldEmail
}fn user_validator(input: InputUser) {
use age <- valid.check(input.age, valid.int_min(13, #(FieldAge, "Should be at least 13")))
use name <- valid.check(input.name, valid.string_is_not_empty(#(FieldName, "Missing name")))
use email <- valid.check(input.email, valid.string_is_email(#(FieldEmail, "Missing email")))valid.ok(ValidUser(age:, name:, email:))
}
```