validus
v1.1.0
Published
An iterable validation library
Downloads
7
Maintainers
Readme
validus
Take an iterable and ensure that the members match a set of constraints.
using
Lets say we have some account data from a form or API request:
const subject = {
type: "accounts",
attributes: {
email: "[email protected]",
name: "",
age: 24
}
}
Consider this list of validations for a new account:
const validations = {
email: {
"You must have an email": pathSatisfies(isPresent, ["attributes", "email"]),
"You must be a Google Employee": pathSatisfies(both(isPopulated, endsWith("@google.com")), ["attributes", "email"]),
"You can't have suffix address": pathSatisfies(both(isPopulated, lacksText("+")), ["attributes", "email"]),
},
name: {
"You must have a name": pathSatisfies(isPresent, ["attributes", "name"]),
},
age: {
"You must have an age": pathSatisfies(isPresent, ["attributes", "age"]),
"You must be older than 30": pathSatisfies(both(isPresent, lt(30)), ["attributes", "age"]),
},
friends: {
"You must have at least one friend": pathSatisfies(both(isPresent, isPopulated), ["attributes", "friends"]),
},
}
Now you add water:
validates(validations)(subject)
Which results in this payload:
{
email: [
"You must be a Google Employee",
"You can't have suffix address"
],
name: [
"You must have a name"
],
age: [
"You must be older than 30"
],
friends: [
"You must have at least one friend"
],
}
You can also do partial validation, say for form inputs:
validates(validations)("email")(subject)
Which returns:
[
"You must be a Google Employee",
"You can't have suffix address"
]