0.0.13-alpha • Published 4 years ago

react-action-validation v0.0.13-alpha

Weekly downloads
13
License
MIT
Repository
github
Last release
4 years ago

react-payload-validation

Validates the payload of a dispatched action

  • Installation
  • Making validators
  • Packing validators
  • Configuration

Usage

You can use the validation using the validationGate middleware or by creating an instance of the validator if you want to use it out of the context of the redux.

1- Installation

npm install --save react-action-validation

2- Making Validators

Making validators is easy, you create a class which is extended from to base Validator class, and add the rules property and write your own rules. be sure you already installed @hapi/joi.

npm install --save @hapi/joi
  • Import Joi.
  • Create a class from Validator.
  • Write your own rules based on @hapi/joi docs.
  • Assign the validation to a type (or as many types you want).
// validations/auth/LoginRequest.js

import Joi from '@hapi/joi';
import { Validator, assign } from 'react-action-validation';

class LoginRequestValidation extends Validator {
  rules = {
    username: Joi.string(),
    password: Joi.string(),
  };

  accept(store, action){
    console.log(`${action.type} accepted!`);
    store.dispatch({
      type: 'LOGIN_ACCEPTED',
      payload: 'credentials are valid',
    });
  }

  reject(store, action){
    console.log(`${action.type} rejected!`);
    store.dispatch({
      type: 'LOGIN_REJECTED',
      payload: 'credentials are invalid',
    });
  }
}

export default assign('LOGIN_REQUEST')(LoginRequestValidation);

Note: the assign function accepts array to assign the validation to multiple types

export default assign(['FOO_TYPE', 'BAR_TYPE'])(CustomValidation);

Note: I recommend you to separate the validation directories from your component and other layers of your app. so in this example, the validators are in a directory called validations in the root of my app.

3- Packing validators

To register al the validators to the validationGate middleware, you should pack them all in an object and export it.

// configureValidation.js
import FooValidation from 'path/to/FooValidation';
import BarValidation from 'path/to/BarValidation';

export default {
  ...FooValidation,
  ...BarValidation
};

4- Configuration

First of all you need to add the validationGate to your middlewares.

// ...

import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';

// ...

import { validationGate } from 'react-action-validation';

// ...

import validations from 'path/to/configureValidation';

// ...

const validator = validationGate(validations);

// ...

const middlewares = [
  validator,
  // other middlewares
]

const store = createStore(
  reducer,
  applyMiddleware(middlewares)
)

// rest unchanged

Using out of redux

You're also able to use it without any custom validation classes and middleware, you can simply create an instance from the Validator class and pass your rules.

import React, {useState} from 'react';
import Joi from '@hapi/joi';
import { Validator } from 'react-action-validation'

const MyFormComponent = props => {
  const [name, setName] = useState('');
  const [message, setMessage] = useState('');

  const handleSubmit = () => {
    const rules = {
      name: Joi.string(),
    }
    const validator = new Validator(rules);
    validator.validate({
      name
    })
    .then(() => setMessage('name is valid'))
    .catch(() => setMessage('name is invalid'));
  }

  return (
    <form onSubmit={handleSubmit} {...props}>
      <input
        placeholder="enter your name"
        value={name}
        onChange={e => setName(e.target.value)}
      />
      <button type="submit">submit</button>
      {!!message && <p>{message}</p>}
    </form>
  );
};

export default MyFormComponent;