Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-action-validation

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-action-validation

validates the payload of the dispatched action

  • 0.0.13-alpha
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
12
Maintainers
1
Weekly downloads
 
Created
Source

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;

Keywords

FAQs

Package last updated on 11 Jul 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc