Created
September 25, 2020 20:41
-
-
Save rulyaryu/b209e2b00624452dd64e684b30c1ad71 to your computer and use it in GitHub Desktop.
validation example with crocks js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import('https://cdn.jsdelivr.net/npm/@esm-bundle/crocks/esm/index.js') | |
.then(crocks => { | |
const { | |
Result, | |
liftN, | |
constant, | |
identity, | |
applyTo, | |
defaultTo, | |
map, | |
ifElse | |
} = crocks.default; | |
const { Ok, Err } = Result; | |
const buildValidator = (pred, errMessage) => | |
ifElse(pred, | |
Ok, | |
constant(Err([errMessage])) | |
) | |
const isLengthInRange = (min, max) => str => str.length > min && str.length < max | |
? Ok(str) | |
: Err([`String needs to be in range ${min} | ${max}`]) | |
const stringIsShort = len => buildValidator(str => str.length >= len, 'string is to short') | |
const stringIsLong = len => buildValidator(str => str.length <= len, 'string is to long') | |
const isRequired = str => str ? Ok(str) : Err(['field is required']) | |
const isValid = (validators = []) => value => | |
liftN( | |
validators.length, | |
identity, | |
...validators.map( | |
applyTo(value) | |
) | |
) | |
// console.log(isValid([isRequired, isLengthInRange(4, 6)])('ssssw')) | |
console.log( | |
isRequired('sssssw') | |
.chain(isValid([stringIsShort(3), stringIsLong(5)])) | |
) | |
// console.log( | |
// map(applyTo('ddd'), | |
// [isLengthInRange(4, 6), isRequired]) | |
// ) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment