Validstate

Validstate

GitHub license npm version PRs Welcome Build Status

Validstate is a javascript plugin for React+Redux applications to quickly validate state.

  • Single DefinitionValidstate puts all of your validations in one place to keep the logic of your actions clean.
  • Prepackaged ValidationFunctions Validstate comes out of the box with several validation functions built in.
  • ExtendableCan't find the function you need? That's okay cause Validstate makes it easy to use your own custom validators.

Installation:

Validstate is available as the validstate package on npm. So installation is as easy as...

$ npm install validstate --save

Basic Usage:

Defining Validations

validations_config.js

The first thing you will need to do is create a validations config file that will hold all of your applications validation rules. For example. If you have an account creation form that you would like to validate before a user can create an account, you could set up your validations config with something like this.

const VALIDATIONS = {
  account: {
    name: { required: true },
    email: { email: true },
    password: { minLength: 8 },
  }
}
export default VALIDATIONS;

The validations config is simply a constant that is storing a json object of each rule.

Keep in mind that Validstate is not simply a form validator, but a state validation plugin. You can also add rules to validate whether the state is in a place to allow the app to continue or decline a user interaction.

If your app is aware of user roles you could also add this rule to your VALIDATIONS constant and check whether a user is permitted in a certain area of your app.

...

},
adminAccess: {
  permissions: {
    includes: "ACCOUNT_CONTROL"
  }
}

Initializing Validstate

Once you have your validation rules created you need to wire up Validstate inside of your app. At your app entry point include the Validstate package and the validstate rules you created.

import Validstate from 'validstate';

import validationConfig from '../validstate/validations_config';

Now initialize the Validstate and pass in your redux store using:

const store = createStore(reducers,{}, applyMiddleware(...));

Validstate.init(validationConfig, store);

Inserting the Validstate Reducer

Finally import the Validstate reducer into the Redux combineReducers function.

Note: In order for Validstate to ignore its own state when running validations be sure to use the validstate: key.
import { ValidstateReducer } from 'validstate';

export default combineReducers({
  validstate: ValidstateReducer
});

Running Validations

my_awesome_component.js

Inside of your component import Validstate

import Validstate from 'validstate';

and then create an event method like normal.

submit(event){
  event.preventDefault();
  if(Validstate.validate('account')){
    this.props.submitAccount(); //Valid
  } else {
    //Invalid
  }
}

You can use

Validstate.validate(validation_name);

anywhere in your application to run that validation and update the validstate.

Checking Validstate

Once your validations run you can check that your state is valid. Set up your mapStateToProps function and add your validstate reducer.

const mapStateToProps = (state) => {
  let { name, email, password } = state.auth;
  let validstate = state.validstate;
  return { name, email, password, validstate};
};

Now you have access to the valid properties inside of your props.

<Input label="Name" name="Name" valid={this.props.validstate.account.name.valid} value={this.props.name} onChange={this.onNameChange.bind(this)} type="text" />

Validations:

Required

– Makes the element required.

Minlength

– Makes the element require a given minimum length.

Maxlength

– Makes the element require a given maximum length.

Rangelength

– Makes the element require a given value range.

Min

– Makes the element require a given minimum.

Max

– Makes the element require a given maximum.

Range

– Makes the element require a given value range.

Step

– Makes the element require a given step.

Email

– Makes the element require a valid email

Number

– Makes the element require a decimal number.

Numeric

– Checks for the value to either be a number or string value of a number

Integer

– Checks for the value to be positive or negative non decimal

Digits

– Makes the element require digits only.

Equalto

– Soft compare of one value to another

Isequalto

– Strong comparison of one value to another

Includes

– Requires the array value to include a specific element.

Custom

– Evaluate a user defined function.

Creditcard

– Makes the element require a credit card number.

Regex

– Checks to make sure the value matches a given regex

Phoneus

– Validate for valid US phone number.

Options:

Custom Messages

Validstate comes with default response messages for each type of validation rule, but you can also add custom messages to each validation by passing in the _messages option.

const VALIDATIONS = {
  account: {
    name: { required: true },
    email: { email: true },
    password: { minLength: 8 },
    _messages: {
      name: { 
        required: "Please let us know your name so we can address you properly.",
      }
    }
  }
export default validations;

Changelog:


Unreleased

  • Ability to add custom validation messages on nested objects
  • Adds requireGroup rule
  • Adds elementOf rule
  • Fix state properties cross reducer collision
  • Find validstate reducer based on state default

1.1.0 - 2018-09-04

Added

  • Adds the ability to run validations on nested objects (nth) levels deep.
  • Adds validations for American phone numbers, credit cards, value includes, and regex.
  • Updates validstate docs with new validations

Changed

  • Custom validation messages are not currently available on nested objects, only single level.

1.0.0 - 2017-11-01

  • Initial Public Release