Giter Site home page Giter Site logo

nucleartide / react-validated-proxy Goto Github PK

View Code? Open in Web Editor NEW
8.0 2.0 0.0 92 KB

(unmaintained, don't use) React <Validate> component based on ES6 Proxy.

License: MIT License

HTML 2.22% TypeScript 65.69% CSS 16.01% JavaScript 16.08%
proxy typescript es2015 validations changeset react reactjs

react-validated-proxy's Introduction

react-validated-proxy

An approach to form validation in React that makes use of ES6 Proxy, by way of @poteto's validated-proxy library.

react-validated-proxy exports a single component <Validate>, which you can use to validate changes to any object.

Install

Note: this library is in alpha and is not ready for production use.

$ npm i react-validated-proxy

Example

import Validate from 'react-validated-proxy';
import { isPresent, hasLength } from './validations';

const user = {
  firstName: 'Billy',
  lastName: 'Bob',
  // ...
};

const Adult = {
  firstName: [isPresent(), hasLength({ min: 2 })],
  lastName: [isPresent(), hasLength({ min: 2 })],
  // ...
};

<Validate model={user} as={Adult}>
  {({ model, set, reset, isPristine, hasErrors, flush }) => (
    <form onSubmit={flush}>
      <input type="text" value={model.firstName} onChange={e => set('firstName', e.target.value)} />
      <input type="text" value={model.lastName} onChange={e => set('lastName', e.target.value)} />
      <button type="submit" disabled={isPristine || hasErrors}>Save</button>
      <button type="button" onClick={reset}>Reset</button>
    </form>
  )}
</Validate>

See the full code for this example under example/. You can also clone this repo and run npm install && npm start to see the example running live.

Rationale

ES6 Proxies have many cool use cases – one of which is validating changes to objects. You can modify an object as you normally would, and a Proxy can intercept those modifications to add custom behavior.

In the case of this library, the <Validate> component accepts a model object, as well as a map of validations in the format defined by validated-proxy. <Validate> will then wrap your model in a Proxy, and pass the Proxy to your children render prop. You can then interact with the Proxy as your model, but with the added benefit of knowing when and why changes to the model are invalid. (Specifically, you can easily retrieve error messages from the Proxy.)

react-validated-proxy owes its existence to validated-proxy and ember-changeset by Lauren Tan. It's mostly an experiment in distilling ember-changeset to its framework-agnostic core.

API

<Validate model={T} as={IValidationMap}>...</Validate>

Pass in a data model that you want to validate, as well as a validation map of validators for your data model. The validation map should be in the format expected by validated-proxy.

const user = {
  firstName: 'Jim',
  lastName: 'Bob',
  age: 15,
};

const Adult = {
  firstName: [isPresent(), hasLength({ min: 2 })],
  lastName: [isPresent(), hasLength({ min: 2 })],
  age: isNumber({ op: '>=', value: 18 }),
};

<Validate model={user} as={Adult}>
  {({ model, set, reset, isPristine, hasErrors, flush }) => (
    <form>{/* ... */}</form>
  )}
</Validate>

<Validate> accepts a render prop as its children, and will pass the wrapped model (and some helper properties and functions) to the render prop:

interface HelperProps {
  model: BufferedProxy
  set: <T>(name: string, value: T) => void
  reset: () => void
  isPristine: boolean
  hasErrors: boolean
  flush: () => void
}

Jason Tu · GitHub @nucleartide · Twitter @nucleartide

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.