Skip to content

Instantly share code, notes, and snippets.

@LeoAref
Last active July 11, 2017 15:06
Show Gist options
  • Save LeoAref/46ae9db46b721c74502ec123d77c2bcd to your computer and use it in GitHub Desktop.
Save LeoAref/46ae9db46b721c74502ec123d77c2bcd to your computer and use it in GitHub Desktop.
React form validation
import isObject from 'lodash/fp/isObject';
import isBoolean from 'lodash/fp/isBoolean';
// this is a naive implementation
export function validateData(data, rules) {
let errors = {};
const isValid = Object.keys(rules).reduce((_isValid, key) {
const error = validateField(data[key], rules[key]);
if (error) {
errors[key] = error;
}
return isValid && !error;
}, true);
return { isValid, errors };
}
// this also is a naive implementation
export function validateField(value, rule) {
if (isBoolean(rule) && rule) {
return value ? null : 'This field is required';
}
if (isObject(rule)) {
if (rule.required) {
return value ? null : 'This field is required';
}
if (rule.email) {
return isValidEmail(value) ? null : 'Please provide a valid email';
}
// other rules...
}
}
export function isValidEmail(value) {
// check if the email is valid according to RegExp
}
import React, { Component } from 'react';
import { validateData } from './form-utils';
class RegisterForm extends Component {
state = {
errors: {}
};
validationRules = {
name: true,
email: {
email: true,
requied: true
},
password: true,
password2: {
required: true,
equals: 'password'
}
};
handleSubmit = evt => {
evt.preventDefault();
const { isValid, errors } = validateData(this.props.data, this.validationRules);
if (isValid) {
this.props.register(this.props.data);
}
this.setState({ errors });
}
render() {
return (
<form onSubmit={this.handleSubmit} noValidate>
<SuperInput
type='text'
value={this.props.data.name}
placeholder='Your name'
error={this.state.errors.name}
onChange={this.props.onChange}
/>
<SuperInput
type='email'
value={this.props.data.name}
placeholder='Your email'
error={this.state.errors.email}
onChange={this.props.onChange}
/>
<SuperInput
type='password'
value={this.props.data.password}
placeholder='Your password'
error={this.state.errors.password}
onChange={this.props.onChange}
/>
<SuperInput
type='password'
value={this.props.data.password2}
placeholder='confirm password'
error={this.state.errors.password2}
onChange={this.props.onChange}
/>
<button type='submit'>Submit</button>
</form>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment