0.1.0 • Published 9 years ago
react-revalidate v0.1.0
react-revalidate
Validate React components with revalidate.
React-revalidate makes integrating your React components with revalidate simpler. The API is still a WIP, but for now react-revalidate exports a HOC (higher order component) that validates a component's props according to a validate function generated from revalidate.
Install
$ npm install --save react-revalidateUsage
Use the validateComponent function to create a new component that validates
its own props. validateComponent is a curried function that takes a validate
function as the first argument and an optional options object as the second
argument. The returned function then takes your component as the only argument.
The wrapped component has a new prop called errors that contains any prop
validation errors.
// ES2015 imports
import React from 'react';
import { validateComponent } from 'react-revalidate';
import {
  combineValidators,
  composeValidators,
  isAlphabetic,
  isNumeric,
  isRequired,
} from 'revalidate';
// CJS imports
const React = require('react');
const validateComponent = require('react-revalidate').validateComponent;
const r = require('revalidate');
const combineValidators = r.combineValidators;
const composeValidators = r.composeValidators;
const isAlphabetic = r.isAlphabetic;
const isNumeric = r.isNumeric;
const isRequired = r.isRequired;
// Usage
function NameTag({ name, age, errors, onUpdateName, onUpdateAge }) {
  return (
    <form>
      <div>
        <input type="text" value={name} onChange={onUpdateName} />
        {errors.name && <div>{errors.name}</div>}
      </div>
      <div>
        <input type="text" value={age} onChange={onUpdateAge} />
        {errors.age && <div>{errors.age}</div>}
      </div>
    </form>
  );
}
const validate = combineValidators({
  name: isRequired('Name'),
  age: composeValidators(
    isRequired,
    isNumeric
  )('Age'),
});
const WrappedNameTag = validateComponent(validate)(NameTag);
// ES2015 export
export default WrappedNameTag;
// CJS export
module.exports = WrappedNameTag;Missing name prop:
render((
  <WrappedNameTag
    age="10"
    onUpdateName={onUpdateName}
    onUpdateAge={onUpdateAge}
  />
), document.getElementById('main'));Missing age prop:
render((
  <WrappedNameTag
    name="Tucker"
    onUpdateName={onUpdateName}
    onUpdateAge={onUpdateAge}
  />
), document.getElementById('main'));Invalid age prop:
render((
  <WrappedNameTag
    name="Tucker"
    age="abc"
    onUpdateName={onUpdateName}
    onUpdateAge={onUpdateAge}
  />
), document.getElementById('main'));Missing both props:
render((
  <WrappedNameTag
    onUpdateName={onUpdateName}
    onUpdateAge={onUpdateAge}
  />
), document.getElementById('main'));0.1.0
9 years ago