Need help with simple-react-validator?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

217 Stars 73 Forks MIT License 340 Commits 22 Opened issues


A simple react form validator inspired by Laravel validation.

Services available


Need anything else?

Contributors list

Simple React Validator

A simple react and react native form validator inspired by Laravel validation.

View on NPM »

Powered by Dockwa


Simple React Validator is exactly as it sounds. We wanted to build a validator for react that had minimal configuration and felt natural to use. It's configuration and usage is similar to the Laravel PHP framework and make validation as easy as one line.

Working Example


  1. Usage
  2. Setup
    1. Public Methods
    2. onBlur
    3. Conditional Fields
    4. React SFC's and Hooks
    5. React Native
  3. Rules
  4. Options
    1. Element
    2. Class Name
    3. Messages
    4. Validators
    5. Auto Force Update
    6. Localization
  5. Custom Validators


Open the

file for more usage examples of the library or check out the Example


npm install simple-react-validator --save


bower install simple-react-validator --save

3 Easy Steps

  1. Import and Initialize the validator.

    import SimpleReactValidator from 'simple-react-validator';
    componentWillMount: function() {
    this.validator = new SimpleReactValidator();
    constructor() {
    this.validator = new SimpleReactValidator();
  2. Add validation rules under inputs. The

    method accepts 5 arguments:
  3. Field Name: A unique underscored string that gets replaced in the messaging as the name of the field.

  4. Value: Usually the state of the current field.

  5. Rules String: A pipe separated list of rules to apply to the string.

  6. Options (Optional): Object of options same as the default options.

this.validator.message('title', this.state.title, 'required|email')

Example: ```jsx render() { return (

Write a Review

    {/**********   This is where the magic happens     ***********/}
    {this.validator.message('title', this.state.title, 'required|alpha')}

{/**********   This is where the magic happens     ***********/}
{this.validator.message('email',, 'required|email', { className: 'text-danger' })}
{/**********   This is where the magic happens     ***********/}
{this.validator.message('review',, 'required|min:20|max:120')}
Save Review

); } ```

  1. Check if the validation passes when submitting and turn on messaging if it fails. Once messaging is turned on, validation messages will change and update as the user types.
    submitForm() {
    if (this.validator.allValid()) {
    alert('You submitted the form and stuff!');
    } else {
    // rerender to show messages for the first time
    // you can use the autoForceUpdate option to do this automatically`

There is another method you can use to check if a single field is valid or not.

if (this.validator.fieldValid('email')) {
  // booya this field is valid!

Note: autoForceUpdate

As of v1.1.0 you can initialize the the constructor with the

option and pass it react instance that is responsible for the state. This will automatically call the
for you when
, and
are called. ```javascript constructor() { this.validator = new SimpleReactValidator({autoForceUpdate: this}); }
#### 1. Available Public Methods
`getErrorMessages()` Returns a JS object, key being the field name, value being the error message.

showMessages() Turns on showing messages for all messages.

hideMessages() Turns off showing messages for all messages.

showMessageFor(field) Turns on showing messages for a specific field. Useful for onBlur.

hideMessageFor(field) Turns off showing messages for a specific field. Useful for onBlur.

allValid() Returns a boolean if all the fields pass validation or not.

fieldValid(field) Checks if a single field is valid or not.

purgeFields() Empties the validation object for conditional fields.

messageWhenPresent(message, options = {}) Show a message when the message is set, good for ajax validation errors.

check(value, validations) A simple way of checking a value against a built in validation rule. Does not add to the validator, just gives a true / false return value.

message(field, value, validations, options = {}) How you define validation rules and add messages into the form.

2. onBlur

You can use the react onBlur action to show individual fields once the input is blurred. Use the showMesssageFor or hideMessageFor methods.

  <input value="{}" onchange="{/*" update email onblur="{()"> this.validator.showMessageFor('email')} /&gt;
  {this.validator.message('email',, 'required|email')}

<h4>3. Conditional Fields</h4>

<p>A field is added to validator via the above </p><pre>message</pre> method. But sometimes you want to conditionally add and remove validation as the form is completed. For this you can use the <pre>purgeFields</pre> method to clear all validator before each render so only the fields added during that render are validated.
<pre class="language-jsx">render() {
  return (
      <div classname="form-group">
        <label>Address Line 1</label>
        <input classname="form-control" value="{this.state.title}" onchange="{this.setTitle}">
        {this.validator.message('title', this.state.title, 'required|alpha')}
      <button classname="btn btn-primary" onclick="{this.submitForm}">Save Review</button>
<h4>4. React Hooks</h4>

<p>SimpleReactValidator is a class but if you instantiate a class in a stateless React component it will do this on every render (losing any message information that may have been added). </p>

<p>useRef: instruct React to treat SimpleReactValidator as a singleton:
const simpleValidator = useRef(new SimpleReactValidator())</p>

<p><input name="name" value="{}" onchange="{handleInputChange}" onblur="{()=">simpleValidator.current.showMessageFor('name')} /&gt;
{simpleValidator.current.message('name',, 'required')}

For more detail see issue: #97

5. React Native

You need to wrap validator with

  {this.validator.message('title', this.state.title, 'required|alpha')}


This is the list of all the rules you can validate form inputs against. When using multiple rules, separate them with a pipe

. When adding options, append a colon to the rule and separate options with commas. Examples:
. You can apply the rules via an array like
['required', {max: 20}, {min: 120}]
['required', {in: ['stu', 'stuyam']}]
. This is necessary for things like the regex validator where you may be using pipes or commas in the regex and would conflict with the rule string.


Must be a JavaScript true, good for required check boxes.


Must be after date. See Date for info on accepted date values.


Must be after or on date. See Date for info on accepted date values.


Must only container letters.


Must only container letters and spaces.


Must only container letters and numbers.


Must only container letters, numbers, and spaces.


Must only container letters, numbers, dashes, and underscores.


Must only container letters, numbers, dashes, underscores, and spaces.


Must be a JavaScript Array.


Must be before date. See Date for info on accepted date values.


Must be before or on date. See Date for info on accepted date values.


Must be between two values. See Size for info on how size is calculated and how options work.


Must be a JavaScript Boolean.


Must be a valid credit card expiration date. Ex. 10/18 or 10/2018


Must be a valid credit card number. Ex. 4242424242424242 or 4242 4242 4242 4242


Must be a valid currency. Dollar signs and commas are optional. Ex. 4.25, $3000 or $3,245,525.12


Must be a date type momentjs date. Requires Momentjs


Must be a date on a specific date.
Options: date must be a momentjs date object.


Must be a valid email format.


Must match a string in options.
Options: list of values it must match.


Must be an integer value.


Must not be greater than max. See Size for info on how size is calculated and how options work.


Must not be less than min. See Size for info on how size is calculated and how options work.


Must NOT match a string in options.
Options: list of values it must not match.


Must NOT match a regex.
Options: regex it must not match.
Note: if your regex uses a | or , or other special characters use the array syntax to define the rule.


Must be a number of any type.
Positive numbers: "numeric|min:0,num"
Negative numbers "numeric|max:0,num"


Must be a valid phone number format. Ex. (508) 555-1234 or 5085551234


Must match a regex.
Options: regex it must match.
Note: if your regex uses a | or , or other special characters use the array syntax to define the rule.


Must be present, use with other validators to require them.


Must be of a particular size. Can be a string length, array length, or number.
Options: type is optional and defaults to

. There are 3 types 'string', 'num', and 'array'. String is length of string, num is size of number, array is length of array.


Must be of type string.


Must be of JavaScript type specified in the options.
Options: compare the type of the value given to the type provided. Use array syntax to define the type else it will always be type string.


Must be a valid url. Ex. or


The Simple React Validator can receive an options object when initialized or as the fourth parameter when defining a validator. There are 4 options you can provide.

1. element:

Accepts a block where you can return the default element that you want to wrap the message from a validator message. The default element is

. If you are using React Native the default will be just the message the gets returned. You can also set
element: false
to just return a message. * Takes 2 params * message: The message coming from the validator. * className (optional): Will optionally be provided so you can change the className on a per validation basis.
this.validator = new SimpleReactValidator({
  element: message => 
// OR element: (message, className) =>

2. className:

String of classes to be passed into an element, default is

and can be overriden.

3. messages:

Accepts an object to override validation messages. It also accepts a default which will override all messages.

this.validator = new SimpleReactValidator({
  messages: {
    email: 'That is not an email.'
    // OR
    default: 'Validation has failed!'  // will override all messages

4. validators:

Accepts an object of custom validators. See Custom Validators for more info on defining custom validators.

5. autoForceUpdate:

Accepts a react instance and will automatically be called when messages are shown and hidden automatically. More on autoForceUpdate

6. locale:

Accepts a string with the localized messages of your choice. For this to work, the correct language file also needs to be loaded into your front end. Current Supported Languages. To contribute to translating the project use this file as a template.

// sets french default validation messages.
this.validator = new SimpleReactValidator({locale: 'fr'});
You can apply custom messages with the messages option. However you can also apply a custom language that you can later select with the
class method.
SimpleReactValidator.addLocale('klingon', {
  accepted: 'Hab SoSlI’ Quch!',
  email: 'Heghlu’meH QaQ jajvam'
this.validator = new SimpleReactValidator({locale: 'klingon'});

Custom Validators

You can write custom rules that you can use the validate. A rule has 4 options: 1. message: The message the will be shown when the validation fails. :attribute will be replaced by the humanized name that your provide of the attribute you are validating (supports snake_case or camelCase). 2. rule: Accepts a block that returns true if validator passes and false if it fails. * Takes 3 params * val: The value that is being validated. * params: An array containing the params passed into the validator. * validator: The validator object, allows you to access helper methods such as

validator.helpers.textRegex(val, regex)
which returns true or false if the regex passes. 3. messageReplace (optional): Accepts a block uses to modify and return the message on the fly. * Takes 2 params * message: The message provided above. * params: An array containing the params passed into the validator. 4. required (optional): True if you want the validator to be implicitly required when it is applied. All validators are not required by default. The equivalent of adding
to each validation definition.


constructor() {
  this.validator = new SimpleReactValidator({
    validators: {
      ip: {  // name the rule
        message: 'The :attribute must be a valid IP address and must be :values.',
        rule: (val, params, validator) => {
          return validator.helpers.testRegex(val,/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/i) && params.indexOf(val) === -1
        messageReplace: (message, params) => message.replace(':values', this.helpers.toSentence(params)),  // optional
        required: true  // optional


render: function() {
  return (

Give Me Your IP

{this.validator.message('ipAddress', this.state.ip, 'required|ip:')}
); },

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.