Skip to content

Instantly share code, notes, and snippets.

@alanbsmith
Created February 27, 2017 20:11
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 alanbsmith/d7f31ebd0dc37106baef63369badfb1f to your computer and use it in GitHub Desktop.
Save alanbsmith/d7f31ebd0dc37106baef63369badfb1f to your computer and use it in GitHub Desktop.
React Form Validation Patterns

React Form Validation Patterns

Intro

Basic Form Validation

We'll start with basic form validation to get a handle on how the overall pattern works. Below is a basic login form without any validation built in. We're using controlled inputs for the email and password fields.

import React, { Component, PropTypes } from 'react';

class BasicLoginForm extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      email: '',
      password: '',
    };
  }
  
  handleSubmit(e) {
    e.preventDefault();
    // stubbed form submission
    console.log('email', this.state.email);
    console.log('password', this.state.password);
  }
  
  render() {
    return (
      <form onSubmit={e => this.handleSubmit(e)}>
        <label>Email</label>
        <input
          name="email"
          onChange={e => this.setState({ email: e.target.value })}
          type="text"
          value={this.state.email}
        />
        <label>Email</label>
        <input
          name="password"
          onChange={e => this.setState({ password: e.target.value })}
          type="password"
          value={this.state.password}
        />
        <button
          type="submit"   
        >
          Submit
        </button>
      </form>
    );
  }
}

export default BasicLoginForm;

Now let's add some validations. We'll start by adding some state to track errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment