• Stars
    star
    363
  • Rank 117,374 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Elegant and composable validations

revalidate

npm Travis branch Codecov

Elegant and composable validations.

Revalidate is a library for creating and composing together small validation functions to create complex, robust validations. There is no need for awkward configuration rules to define validations. Just use functions.

All right. No more upselling. Just look at an example ❤️.

// ES2015
import {
  createValidator,
  composeValidators,
  combineValidators,
  isRequired,
  isAlphabetic,
  isNumeric
} from 'revalidate';

// Or ES5
var r = require('revalidate');
var createValidator = r.createValidator;
var composeValidators = r.composeValidators;
var combineValidators = r.combineValidators;
var isRequired = r.isRequired;
var isAlphabetic = r.isAlphabetic;
var isNumeric = r.isNumeric;

// Usage
const dogValidator = combineValidators({
  name: composeValidators(
    isRequired,
    isAlphabetic
  )('Name'),

  age: isNumeric('Age')
});

dogValidator({}); // { name: 'Name is required' }

dogValidator({ name: '123', age: 'abc' });
// { name: 'Name must be alphabetic', age: 'Age must be numeric' }

dogValidator({ name: 'Tucker', age: '10' }); // {}

Install

Install with yarn or npm.

yarn add revalidate
npm install --save revalidate

Getting Started

Docs

Revalidate has a host of options along with helper functions for building validations and some common validation functions right out of the box. To learn more, check out the docs at revalidate.jeremyfairbank.com.

Redux Form

Just one more example! You might have heard about revalidate through Redux Form. Revalidate was originally conceived as a library for writing validation functions for Redux Form. Revalidate is still a great companion to Redux Form! Here is the simple synchronous form validation from Redux Form's docs rewritten to use revalidate:

import React from 'react'
import { Field, reduxForm } from 'redux-form'

import {
  createValidator,
  composeValidators,
  combineValidators,
  isRequired,
  hasLengthLessThan,
  isNumeric
} from 'revalidate'

const isValidEmail = createValidator(
  message => value => {
    if (value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
      return message
    }
  },
  'Invalid email address'
)

const isGreaterThan = (n) => createValidator(
  message => value => {
    if (value && Number(value) <= n) {
      return message
    }
  },
  field => `${field} must be greater than ${n}`
)

const customIsRequired = isRequired({ message: 'Required' })

const validate = combineValidators({
  username: composeValidators(
    customIsRequired,

    hasLengthLessThan(16)({
      message: 'Must be 15 characters or less'
    })
  )(),

  email: composeValidators(
    customIsRequired,
    isValidEmail
  )(),

  age: composeValidators(
    customIsRequired,

    isNumeric({
      message: 'Must be a number'
    }),

    isGreaterThan(17)({
      message: 'Sorry, you must be at least 18 years old'
    })
  )()
})

const warn = values => {
  const warnings = {}
  if (values.age < 19) {
    warnings.age = 'Hmm, you seem a bit young...'
  }
  return warnings
}

const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} placeholder={label} type={type}/>
      {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
    </div>
  </div>
)

const SyncValidationForm = (props) => {
  const { handleSubmit, pristine, reset, submitting } = props
  return (
    <form onSubmit={handleSubmit}>
      <Field name="username" type="text" component={renderField} label="Username"/>
      <Field name="email" type="email" component={renderField} label="Email"/>
      <Field name="age" type="number" component={renderField} label="Age"/>
      <div>
        <button type="submit" disabled={submitting}>Submit</button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>
          Clear Values
        </button>
      </div>
    </form>
  )
}

export default reduxForm({
  form: 'syncValidation',  // a unique identifier for this form
  validate,                // <--- validation function given to redux-form
  warn                     // <--- warning function given to redux-form
})(SyncValidationForm)

More Repositories

1

redux-saga-test-plan

Test Redux Saga with an easy plan.
JavaScript
1,248
star
2

chroma

Ruby gem for color manipulation and palette generation
Ruby
232
star
3

redux-saga-router

A router for Redux Saga
JavaScript
152
star
4

run-elm

Run Elm code from the command line
JavaScript
52
star
5

marionette.component

Manage and create components for your Marionette.js application
JavaScript
36
star
6

fp-basics-in-es6

Code samples for "Functional Programming Basics in ES6" talk
JavaScript
35
star
7

redux-resource

Redux action creator for managing RESTful resources
JavaScript
32
star
8

combos

Generate all possible permutations of an object's key-value pairs
JavaScript
27
star
9

rise-of-async-js-talk

Code samples, demos, and resources for "The Rise of Async JavaScript" talk
JavaScript
26
star
10

react-bind-closures

Bind closures to stateless React components to avoid creating closures at render time
JavaScript
22
star
11

programming-elm.com

Source for programming-elm.com
Elm
19
star
12

arch-elm

Code for talk "Toward a Better Front-end Architecture: Elm"
Elm
19
star
13

fsm-iterator

A finite state machine iterator for JavaScript
JavaScript
16
star
14

website

Source for my personal website
JavaScript
15
star
15

marionette.polymerview

JavaScript
13
star
16

effective-react-testing

JavaScript
12
star
17

whitesimilarity

Ruby gem implementation of the White Similarity Algorithm
C
12
star
18

building-web-apps-with-elm-tutorial

Elm
11
star
19

perchance

A simple maybe monad for JavaScript
JavaScript
10
star
20

elm-workshop

Setup instructions and finished demos for the "Building Web Apps with Elm" workshop
9
star
21

redux-binary

Redux reducer and actions for handling binary state
JavaScript
9
star
22

react-classify

Classify functional React components to use component lifecycle hooks
JavaScript
9
star
23

elm-stream

Fast and simple stream library for Elm
Elm
8
star
24

dotfiles

Vim Script
7
star
25

redux-glue

Glue together Redux actions to create testable, sequenced actions
JavaScript
6
star
26

public-apis

Simple web app for finding public APIs
JavaScript
6
star
27

photomosaic

Web app for computing photomosaics in the browser
JavaScript
5
star
28

building-resilient-api-driven-elm

Elm
5
star
29

babel-plugin-transform-underscore-arrow-functions

Transform arrow functions with an underscore param into param-less functions
JavaScript
4
star
30

react-revalidate

Validate React component props with revalidate
JavaScript
4
star
31

elm-demos

Example Elm demo apps to complement future Elm blog posts
Elm
3
star
32

conways-game-of-life

Conway's Game of Life implemented in Elm
Elm
3
star
33

migrate-js-to-elm

JavaScript
3
star
34

meteor-rps

JavaScript
2
star
35

advanced-cypress-testing

JavaScript
2
star
36

_redux-saga-router_5

JavaScript
2
star
37

redux-revalidate

Validate your Redux store state with revalidate
JavaScript
2
star
38

measurb

Handle units of measurement in Ruby with ease!
Ruby
2
star
39

fp-in-javascript

Many common functional programming patterns succinctly implemented in JavaScript
JavaScript
2
star
40

modular-react-and-redux-talk

Code samples for the "Modular React and Redux" talk
JavaScript
2
star
41

marionette.attrsync

JavaScript
1
star
42

node-koa-es6

JavaScript
1
star
43

backbone.directattributes

Direct attributes for Backbone models
1
star
44

pat-packet-visits-ruby-rails

Ruby
1
star
45

playit

Control audio players on websites with your keyboard's Play/Pause key
JavaScript
1
star
46

state-side-effects-and-redux

Code samples for "State, Side Effects, and Redux. Oh my!" talk
JavaScript
1
star
47

es7-and-beyond-talk

JavaScript
1
star
48

bundle-with-webpack-talk

Resources for the talk "Bundle the Web with Webpack"
JavaScript
1
star
49

dynamically-sassy-demos

Ruby
1
star
50

orchestrating-apps-angular

JavaScript
1
star