redux-validator
Action parameter validator middleware for redux
Installation
npm i redux-validator --save
How to use
Add middleware to your store
; const validator = ;const createStoreWithMiddleware = createStore;const store = ;
If you use other middleware, apply redux-validator
first to prevent unexpected errors.
;; const validator = ;const createStoreWithMiddleware = createStore;const store = ;
Add validators to your actions
const validAction = type: ADD_TODO payload: text: 'Sample todo' complete: false meta: validator: text: 0 <= textlength msg: 'Cannot add an empty todo' complete: typeofcomplete === "boolean" msg: 'Complete must be true or false' const result = ; // validation success and dispatch completes
redux-validator
is Flux Standard Action compatible.
The properties in action.payload
are validated against the functions provided in the action.meta.validator
map. If validation of any property fails, the dispatch is aborted and an object containing error information is returned.
const invalidAction = type: ADD_TODO payload: text: '' meta: validator: text: 0 <= textlength msg: 'Cannot add an empty todo' const result = ; // dispatch aborted and error returned:// result = {// err: 'validator',// msg: 'Cannot add an empty todo',// param: 'text',// id: 0// }
Multiple validations may be defined for a single property. The property will be checked against all validators in the array in the order they are declared. The dispatch is aborted and the error returned on the first failing validation.
const action = type: ADD_TODO payload: text: 'Write an awesome react app' meta: validator: text: 0 <= textlength msg: 'Cannot add an empty todo' textlength < 500 msg: 'Todo too long'
Other Examples
Usage with redux-actions
It's very easy to integrate redux-validator
with createAction
from redux-actions:
; const actionCreator = ; const result1 = ;const result2 = ;// dispatchs would abort!// result1 = {// err: 'validator',// msg: 'payload is less than 0',// param: 'payload',// id: 0// }// result2 = {// err: 'validator',// msg: '',// param: 'payload',// id: 1// }
Async actions (thunk support)
; const actionCreator = ; const result1 = ;const result2 = ;// result1 would abort!// result1 = {// err: 'validator',// msg: 'payload is less than 0',// param: 'payload',// id: 0// }// result2 would not abort, and it would continue to pass through thunk middleware// result2 = thunk
API
Middleware Options
validatorKey
Override the default location for the validators in action
objects (default is 'meta'
).
; const validator = ;
paramKey
Override the default location for the parmas in action
objects (default is payload
).
; const validator = ;