Skip to content

Instantly share code, notes, and snippets.

@btnwtn
Created May 2, 2017 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save btnwtn/9d2ea8b7ab0686ab181dbea64b2517f9 to your computer and use it in GitHub Desktop.
Save btnwtn/9d2ea8b7ab0686ab181dbea64b2517f9 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
const mockAPI = {
emailExists(email) {
return new Promise(resolve => setTimeout(resolve(true), 300))
}
}
const validateEmail = async email => new Promise(resolve => {
mockAPI.emailExists(email).then(exists => {
resolve([
email.length === 0 && 'Email is required.',
email.length < 3 && 'Please provide a valid email.',
!email.includes('@') && 'Email must include @ symbol.',
exists && 'Email already exists.'
])
})
})
const validatePassword = async password => new Promise(resolve => {
resolve([
password.length < 8 && 'Password must be at least 8 characters.'
])
})
const rules = {
email: validateEmail,
password: validatePassword
}
const makeValidator = rules => field => async value => {
const validator = rules[field]
if (!validator) throw new Error(`Missing validator for field: ${field}`)
const errors = await validator(value)
return errors.filter(v => v)
}
const validate = makeValidator(rules)
class App extends Component {
state = {
email: {
value: '',
errors: []
},
}
handleChange = (event) => {
const { name, value } = event.target
this.setState(state => {
return {
[name]: {
...state[name],
value
}
}
})
}
validateChanges = async (event) => {
const { name, value } = event.target
validate(name)(value)
.then((errors) => this.setState(state => {
return {
[name]: {
...state[name],
errors
}
}
}))
}
render() {
return (
<form>
<h1>Form Validation w/ Multiple Inputs</h1>
<label>
{'Email: '}
<input
name="email"
type="text"
value={this.state.email.value}
onChange={this.handleChange}
onBlur={this.validateChanges}
/>
</label>
<hr/>
<pre>{JSON.stringify(this.state, null, 2)}</pre>
</form>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment