A BuckleScript implementation of the Folktalevalidation applicative
NOTE: These are not bindings, this a ReasonML implementation of the
Validation applicative.
I wanted a way to do validations for my server side project.
Not all of the Folktale/Validation functions will be implemented. Here is a list of the currently implemented functions:
- map
- apply
- unsafeGet
- getOrElse
- orElse
- concat
- fold
- swap
- bimap
- mapFailure
- toOption
mergesee note in the code.
All implemented functions are found in src/Validation.re, They are all
documented with their Folktale style doc strings.
- Add the bs-validation package to your project.
yarn add bs-validation- Add
bs-validationto yourbsconfig.json
{
"dependencies": [ "bs-validation" ]
}- Enjoy!
The library is exposed as a functor which accepts modules that implement the following type interface:
moduletypeFoldable= {
typet('a);
letconcat: (t('a),t('a)) => t('a);
};All of the examples use an array based implementation of the Foldable type:
moduleFoldableArray= {
typet('a) = array('a);
letconcat= (x, y) =>Belt_Array.concat(x, y);
};You import the module into your project by calling the Validation functor
with your version of the Foldable type.
moduleV=Validation.Make_validation(FoldableArray);Then you can use it to validate all of your things!
letlengthError="Password must have more than 6 characters.";letstrengthError="Password must contain a special character.";letisPasswordLongEnough= (password) =>String.length(password) >6?V.Success(password)
:V.Failure([|lengthError|]);letisPasswordStrongEnough= (password) => {
letregex= [%bs.re"/[\\W]/"];Js.Re.test(password, regex)
?V.Success(password)
:V.Failure([|strengthError|])
};letisPasswordValid= (password) => {
V.Success()|>V.concat(isPasswordLongEnough(password))
|>V.concat(isPasswordStrongEnough(password))
|>V.map((_) =>password)
};
describe("Folketale password validation example",()=> {
test("should return the password",()=> {
letpassword="rosesarered$andstuff";switch (isPasswordValid(password)) {
|Failure(f) => { Js.log(f); fail("unexpected_failure") }
|Success(p) =>Expect.expect(p) |>Expect.toBe(password)
}
});
test("should return a single item failure",()=> {
letpassword="rosesarered";switch (isPasswordValid(password)) {
|Failure(f) =>Expect.expect(f) |>Expect.toBeSupersetOf([|strengthError|])
|Success(_) => fail("unexpected_success")
}
});
test("should return 2 items in the failure list",()=> {
letpassword="foo";switch (isPasswordValid(password)) {
|Failure(f) => {
Expect.expect(f)
|>Expect.toBeSupersetOf([|lengthError, strengthError|])
}
|Success(_) => fail("unexpected_success")
}
});
});