Skip to content

Instantly share code, notes, and snippets.

@JakeLaCombe
Last active February 14, 2018 04:35
Show Gist options
  • Save JakeLaCombe/e9642062bd66fa9de281983d91c887bf to your computer and use it in GitHub Desktop.
Save JakeLaCombe/e9642062bd66fa9de281983d91c887bf to your computer and use it in GitHub Desktop.
React Form Validations

Example Validations

// rules.js
import * as ErrorMessages from './errorMessages.js';

export const required = (text) => {
  if (text) {
    return null;
  } else {
    return ErrorMessages.isRequired;
  }
};

export const mustMatch = (field, fieldName) => {
  return (text, state) => {
    return state[field] == text ? null : ErrorMessages.mustMatch(fieldName);
  };
};

export const minLength = (length) => {
  return (text) => {
    console.log("Checking for length greater than ", length);
    return text.length >= length ? null : ErrorMessages.minLength(length);
  };
};

Rule Function Function

export const ruleRunner = (field, name, ...validations) => {
  return (state) => {
    for (let v of validations) {
      let errorMessageFunc = v(state[field], state);
    
      if (errorMessageFunc) {
        return {[field]: errorMessageFunc(name)};
      }
    }
    return null;
  };
};

export const run = (state, runners) => {
  return runners.reduce((memo, runner) => {
    return Object.assign(memo, runner(state));
  }, {});
};

Implementation

const fieldValidations = [
  ruleRunner("name", "Name", required),
  ruleRunner("emailAddress", "Email Address", required),
  ruleRunner("password1", "Password", required, minLength(6)),
  ruleRunner("password2", "Password Confirmation", mustMatch("password1", "Password"))
];

export default class CreateAccount extends React.Component {
  constructor() {
    // ...
    this.state = {
      showErrors: false,
      validationErrors: {}
    };

    // Run validations on initial state
    this.state.validationErrors = run(this.state, fieldValidations);
  }
  
  handleFieldChanged(event) {
    // update() is provided by React Immutability Helpers
    // https://facebook.github.io/react/docs/update.html
    let newState = update(this.state, {
      [field]: {$set: event.target.value}
    });
    newState.validationErrors = run(newState, fieldValidations);
    this.setState(newState);
  }
    
  handleSubmitClicked() {
    if($.isEmptyObject(this.state.validationErrors) == false) return null;
    // ... continue submitting data to server
  }

  render() {
    return (
      <div>
        <Field
          error={this.errorFor("emailAddress")}
          help="Families are eligible for family package plans"
          required
          isInvalid={this.state.validationErrors("emailAddress")}
        >
          <Input placeholder="Email address" onChange={this.handleFieldChanged} isInvalid={this.state.validationErrors("emailAddress")} />
        </Field>
        
        // Render Name, Password, Submit button, etc. fields
      <div>
    );
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment