Skip to content

Create react form validation lib #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
sudo: false

language: node_js
node_js:
- 6
- 8

before_install:
- npm install codecov.io

after_success:
- cat ./coverage/lcov.info | ./node_modules/codecov.io/bin/codecov.io.js
25 changes: 25 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
## Prerequisites

[Node.js](http://nodejs.org/) >= v4 must be installed.

## Installation

- Running `npm install` in the components's root directory will install everything you need for development.

## Demo Development Server

- `npm start` will run a development server with the component's demo app at [http://localhost:3000](http://localhost:3000) with hot module reloading.

## Running Tests

- `npm test` will run the tests once.

- `npm run test:coverage` will run the tests and produce a coverage report in `coverage/`.

- `npm run test:watch` will run the tests on every change.

## Building

- `npm run build` will build the component for publishing to npm and also bundle the demo app.

- `npm run clean` will delete built resources.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
# react-form-validation
[![Travis](https://img.shields.io/travis/ontohub/react-form-validation.svg)](https://travis-ci.org/ontohub/react-form-validation)
[![Codecov](https://img.shields.io/codecov/c/github/ontohub/react-form-validation.svg)](https://codecov.io/gh/ontohub/react-form-validation)
[![npm version](https://img.shields.io/npm/v/@ontohub/react-form-validation.svg)](https://www.npmjs.com/package/@ontohub/react-form-validation)

# react-form-validation
40 changes: 40 additions & 0 deletions demo/src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
body {
display: flex;
align-items: center;
justify-content: center;
background-color: #efefef;
}

h1 {
font-weight: normal;
}

.field {
box-sizing: border-box;
width: 30rem;
padding: 2em 0;
}

.field .errors {
box-sizing: border-box;
position: absolute;
width: 30rem;
background-color: crimson;
color: white;
font-size: 0.7em;
padding: 0 0.5em;
border-bottom-left-radius: 0.2em;
border-bottom-right-radius: 0.2em;
}

.field.validating input {
background-color: #ddeeff;
}

.field input {
box-sizing: border-box;
display: block;
width: 100%;
font-size: 1.1em;
padding: 0.2em;
}
100 changes: 100 additions & 0 deletions demo/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import React, { Component } from "react";
import { render } from "react-dom";

import "./index.css";
import { Validator, Validate } from "../../src";
import WaitValidation from "../../src/validations/wait-validation";

import _ from "lodash";
const ValidatedField = params => (
<Validate
name={params.name}
invalidates={params.invalidates || []}
rules={params.rules}
render={({ name, onChange, validate, validating, errors, error }) => (
<div
className={[
"field",
(error && "error") || "",
(validating && "validating") || ""
].join(" ")}
>
<input
name={name}
type={params.type}
placeholder={name}
onChange={onChange}
onBlur={validate}
/>
<div className="errors">
{errors.map((e, idx) => <p key={idx}>{e}</p>)}
</div>
</div>
)}
/>
);

class Demo extends Component {
render() {
return (
<div>
<h1>Form validations</h1>
<Validator validators={[WaitValidation]}>
<ValidatedField
name="Username"
rules={f =>
f
.required()
.then(f =>
f
.length({ min: 3 })
.matches(/^[a-z0-9-]+$/, "must consist of only a-z, 0-9, -")
)
.then(f =>
f
.matches(/^[a-z0-9]/, "must not start with a dash")
.matches(/[a-z0-9]$/, "must not end with a dash")
)
.then(f =>
f.waitDebounced(500, 500, "is already taken", false)
)}
/>
<ValidatedField
name="Email"
rules={f => f.required().then(f => f.email())}
/>
<ValidatedField
name="Password"
type="password"
invalidates={["Password confirmation"]}
rules={f => f.required().then(f => f.length({ min: 10 }))}
/>
<ValidatedField
name="Password confirmation"
type="password"
rules={f => f.equals("Password")}
/>
<ValidatedField
name="Admin"
type="checkbox"
rules={f => f.required()}
/>
<Validate
invalidates={[
"Username",
"Email",
"Password",
"Password confirmation",
"Admin"
]}
render={({ validate }) => (
<button onClick={validate}>Validate all</button>
)}
/>
</Validator>
</div>
);
}
}

render(<Demo />, document.querySelector("#demo"));
7 changes: 7 additions & 0 deletions nwb.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
type: 'react-component',
npm: {
esModules: true,
umd: false
}
}
39 changes: 39 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "@ontohub/react-form-validation",
"version": "0.1.0-alpha2",
"description": "validate React forms",
"main": "lib/index.js",
"module": "es/index.js",
"files": [
"css",
"es",
"lib",
"umd"
],
"scripts": {
"build": "nwb build-react-component",
"clean": "nwb clean-module && nwb clean-demo",
"start": "nwb serve-react-demo",
"test": "nwb test-react",
"test:coverage": "nwb test-react --coverage",
"test:watch": "nwb test-react --server"
},
"dependencies": {},
"peerDependencies": {
"lodash": "^4.17.4",
"react": "15.x"
},
"devDependencies": {
"lodash": "^4.17.4",
"nwb": "0.17.x",
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"author": "",
"homepage": "https://github.com/ontohub/react-form-validation",
"license": "MIT",
"repository": "",
"keywords": [
"react-component"
]
}
64 changes: 64 additions & 0 deletions src/Validate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React from "react";
import PropTypes from "prop-types";

export class Validate extends React.Component {
static contextTypes = {
onChange: PropTypes.func,
validate: PropTypes.func,
register: PropTypes.func
};
state = { errors: [], runningValidations: 0 };
constructor(props, context) {
super(props, context);
this.onChange = this.onChange.bind(this);
this.onErrors = this.onErrors.bind(this);
this.validate = this.validate.bind(this);
this.startValidation = this.startValidation.bind(this);
this.stopValidation = this.stopValidation.bind(this);
this.context.register(
this.props.name,
this.props.rules || (f => f),
this.onErrors,
this.startValidation,
this.stopValidation,
this.props.defaultValue || ""
);
}
onErrors(errors) {
this.setState({ errors });
}
startValidation() {
this.setState(({ runningValidations }) => ({
runningValidations: runningValidations + 1
}));
}
stopValidation() {
this.setState(({ runningValidations }) => ({
runningValidations: runningValidations - 1
}));
}
validate() {
this.context.validate([this.props.name, ...this.props.invalidates]);
}
onChange(event) {
let value = event.target.value;
if (event.target.type === "checkbox") {
value = event.target.checked;
}
this.context.onChange(this.props.name, value);
this.validate();
}
render() {
let { render, ...props } = this.props;
return render({
...props,
error: this.state.errors.length > 0,
errors: this.state.errors,
validating: this.state.runningValidations > 0,
validate: this.validate,
onChange: this.onChange
});
}
}

export default Validate;
80 changes: 80 additions & 0 deletions src/Validator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import React from "react";
import PropTypes from "prop-types";
import Field from "./field";
import validate from "./validate-fns";

import defaultValidators from "./validations";

export class Validator extends React.Component {
fields = {};
values = {};
static childContextTypes = {
register: PropTypes.func,
onChange: PropTypes.func,
validate: PropTypes.func
};
constructor(props) {
super(props);
let { validators = [] } = props;
this.validators = [...defaultValidators, ...validators];
this.register = this.register.bind(this);
this.validate = this.validate.bind(this);
this.onChange = this.onChange.bind(this);
}
render() {
return <div>{this.props.children}</div>;
}
register(
name,
rules,
onErrors,
onValidateStart,
onValidateFinish,
defaultValue
) {
this.fields[name] = {
onErrors,
onValidateStart,
onValidateFinish,
rules: rules(new Field(this.validators)),
cancel: () => {}
};
this.values[name] = defaultValue;
}
onChange(name, value) {
this.values[name] = value;
}
validate(names) {
_.each(names, name => {
this.fields[name].onValidateStart();
this.fields[name].cancel();
let cancel = new Promise(resolve => {
this.fields[name].cancel = resolve;
});
let field = this.fields[name];
let validators = field.rules.validators();
let value = this.values[name];
let cb = errors =>
field.onErrors(
_.chain(validators)
.flatten()
.map(validator => errors[validator.id])
.filter()
.value()
);
validate(validators, value, this.values, cb, cancel).then(
this.fields[name].onValidateFinish,
this.fields[name].onValidateFinish
);
});
}
getChildContext() {
return {
register: this.register,
onChange: this.onChange,
validate: this.validate
};
}
}

export default Validator;
Loading