A promising and ridiculously small es6 validator that tree-shakes well and respects your bundle.
Current state: work in progress
npm i @yobta/validator
createValidator(...rules)
– returns sync validatorcreateAsyncValidator(...syncOrAsyncRules)
– returns aync validator
pipe(...rules)
– combines several rules to oneasyncPipe(...syncOrAsyncRules)
– combines several rules to one
-
array(errorMessage)
- creates a array rule, coercing unknown value to arrayitems(...rules)
– validates every array item against rulesmaxItems(limit: Number, errorMessage)
– checks if a array length within a limitminItems(limit: Number, errorMessage)
– checks if a array length within a limitunique(errorMessage)
– requires array to have unique values
-
boolean(errorMessage)
- creates a boolean rule -
constant(value, errorMessage)
- creates a strict equality rule -
date(errorMessage)
- creates a date rulemaxDate(limit: Date, errorMessage)
– checks if a value within a date limitminDate(limit: Date, errorMessage)
– checks if a value within a date limit
-
fallback(defaultValue, ...rules)
- returns adefaultValue
if rules not satisfied, if no rules provided transforms '' orundefined
value to adefaultValue
-
number(errorMessage)
- converts a value to a finiteNumber
or throwsinteger(errorMessage)
– checks if a value is an integermaxNumber(limit: Number, errorMessage)
– checks if a value within a limitminNumber(limit: Number, errorMessage)
– checks if a value within a limit
-
oneOf(new Set([1])), errorMessage)
– checks if simple value in a set -
shape({ key: rule }, errorMessage)
– checks plain object shapedifferent('key', errorMessage)
– creates a rule to check if an object key is not equal to antoher keyidentical('key', errorMessage)
– creates a rule to check if an object key is strictly equal to antoher key
-
required(errorMessage)
— throws a message if a value is an empty string orundefined
-
rule((value, ctx) => {...your custom rule, return value})
— allows creating custom validation rules -
string(errorMessage)
– coerses a simple value to string or throwsemail(errorMessage)
– checks if a string value is an emailmaxCharacters(limit: Number, errorMessage)
– checks if a value length within a limitminCharacters(limit: Number, errorMessage)
– checks if a value length within a limitslug(errorMessage)
– checks if a string value is a slugtest(regExp, errorMessage)
– checks if a value passingregExp
test
asyncShape({ field: syncOrAsyncRule() }, errorMessage)
– resolves valid shape
asyncSubmit(callback)
– executes a callback for a valid form submiteffect(callback)
– executes a callback, returns input valueerrors(callback)
– calls back withYobtaError
success(callback)
– executes a callback whenever the current step have no errorsvalidity(callback)
– maps validation errors to the form inputs, or sends current error to the callback when can't map
form(errorMessage)
- transformsHTMLFormElement
or (form)Event
to a plain objectrule(Number)
– transforms any to number
-
[+] Shape validator
-
[-] Array validator
- [+] items
- [-] contains (do later)
- [+] unique
- [+] minimum items
- [+] maximum items
-
[-] String validator
- [+] minimum characters
- [+] maximum characters
- [-] href (do later)
- [-] credit card number (do later)
- [-] phone number (do later)
- [-] base64 (do later)
-
[+] Number validator
- [+] int
- [+] minimum
- [+] maximum
-
[+] RegExp test
-
[+] FormData
- [+] catch
- [+] identical
- [+] URLSearchParams
- [+] side effect
- [+] validityYobta
- [-] anyOf
We want to fulfill the front-end needs and create functional promise-based validator which is fun to work with.
- Functional
- Universal
- Immutable
- Sync/async
- Coercion (https://ajv.js.org/coercion.html)
- Validate: maps, arrays, strings, numbers, booleans, dates, FormData, URLSearchParams
- Flow control: fall-backs, side effects, logic operators, serializers
We need to get a predictable initial state from the URL, the operation should be sync and silent (no errors) and the state should be a plain object.
const getInitialState = yobta(
urlSearchParamsYobta(),
shapeYobta({
currentTab: [fallback('tab-1', oneOf(()= new Set(['tab-1', 'tab-2', 'tab-3'])))],
myModalIsOpen: [fallback(false, boolean())],
}),
)
const initialState = getInitialState(location.search)
const myStore = createStore('name', initialState)
We need to get a type-safe form data, but the validation operation should be async, because we don't know if one of the fields exists in our database. This operation can produce errors and we need human friendly error messages.
async function confirmPassword (password) (
const response = await fetch(`/api/my-endpoint?password=${password}`)
if (!response.ok) throw new Error('Wrong password')
return password.data.password
)
const validate = asyncYobta(
effect(toggleFormLock),
formYobta()
asyncShape({
password: [
string(),
asyncSubmit(verifyPassword),
],
new: [
string(),
minYobta(6),
maxYobta(16),
matchYobta(passwordRegExp), // make your own RegExp
],
repeat: [
identicalYobta('new')
],
}),
asyncSubmit(sendMyFormAsJSON),
errors(),
validity(console.error), // https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity#examples
effect(toggleFormLock),
)
const myForm = window.getElementByID('myForm')
const [formData, errors] = await validate(myForm)
- [-] Readme for all
- [-] JSDoc for all
- Ajv — Follows json-schema.org specs, great choice for a back-end
- Yup — Popular front-end library
- Shark-Validator — a validator es6, but class-based
- formurai — to be researched
Docs coming soon
Andrey Sitnik Joe Calzaretta Jon Schlinkert John-David Dalton