Skip to content

dsshard/react-validator

Repository files navigation

React Validator

Β 

MIT License Travis CI CodeCov Coverage Status dependencies Status Maintainability BundlePhobia GitHub Release

Simple React form validation.

Data validation on the Node JS side, is also supported.

Need react >=16.3

Example

See more examples here

import React, { useState } from 'react';
import { ValidatorWrapper, rules, ValidatorField } from '@coxy/react-validator';

const validator = React.createRef();

const handleSubmit = () => {
  const { isValid, message, errors } = validator.current.validate();
  if (!isValid) {
    console.log(isValid, message, errors);
    return;
  }
  // Success
};

export default () => {
  const [email, handleChange] = useState('');

  return (
    <ValidatorWrapper ref={validator}>

      <ValidatorField value={email} rules={rules.email}>
        {({ isValid, message }) => (
          <>
            <input value={email} onChange={({ target: { value } }) => handleChange(value)} />
            {!isValid && <div>{message}</div>}
          </>
        )}
      </ValidatorField>

      <ValidatorField value={email} rules={rules.email}>
        <input value={email} onChange={({ target: { value } }) => handleChange(value)} />
      </ValidatorField>

      {/* This is also possible :) */}
      <ValidatorField value={email} rules={rules.email} />

      <button onClick={handleSubmit} type="button">
        Submit
      </button>

    </ValidatorWrapper>
  );
};

See more examples here Β 

Rules

You can create your own rules for validation, with your own error messages

const rules = {
  email: [{
    rule: value => value !== '' && value.length > 0,
    message: 'Value is required',
  }, {
    rule: value => value.indexOf('@') > -1,
    message: '@ is required',
  }]
}

This component has a default set of rules that you can use right away:

name Type description
email Check email for empty string and regexp
password Check password for empty string and length
notEmpty Check if the string is not empty
boolean Will check that the value is present
min function min(3) -> Check the number
max function max(5) -> Check the number
length function length(3, 5) -> Check string length (second parameter is optional)

Β 

Api for React

ValidatorWrapper props

name default required description
ref null no React.ref or useRef
stopAtFirstError false no The validator will stop checking after the first error

Β 

ValidatorField props

name default required description
value undefined yes Value for validation
rules [] yes Array of rules for validation
required true no The field will be required
id null no ID for get field

Β 

React api useValidator

const [isValid, { errors }] = useValidator('test value', rules.email)
console.log(isValid, errors) // false

Β 

Api for inline validation

Validator constructor parameters

name default required description
stopAtFirstError false no The validator will stop checking after the first error

Β 

Validator.addField()

Adds a field for validation

import { Validator } from '@coxy/react-validator';

const validator = new Validator({ stopAtFirstError: true });
const field = validator.addField({
    rules: rules.password,
    value: '',
});

Β 

Validator.getField()

Returns the field by ID

import { Validator } from '@coxy/react-validator';

const validator = new Validator({ stopAtFirstError: true });
const field = validator.addField({
    rules: rules.password,
    value: '',
    id: 'test-field-name'
});
console.log(validator.getField('test-field-name')) // Field Class

Β 

Validator.removeField()

Removes a previously added field

import { Validator } from '@coxy/react-validator';

const validator = new Validator({ stopAtFirstError: true });
const field = validator.addField({
    rules: rules.password,
    value: '',
    id: 'test-field-name'
});

validator.removeField(field);
console.log(validator.getField('test-field-name')) // null

Β 

Validator.validate()

Validates all added fields

import { Validator } from '@coxy/react-validator';

const validator = new Validator({ stopAtFirstError: true });
const field = validator.addField({
    rules: rules.password,
    value: '',
});

console.log(validator.validate());