Git Product home page Git Product logo

formsy-react's Introduction

formsy-react

A form input builder and validator for React JS

I wrote an article on forms and validation with React JS, Nailing that validation with React JS, the result of that was this extension.

The main concept is that forms, inputs and validation is done very differently across developers and projects. This extension to React JS aims to be that "sweet spot" between flexibility and reusability.

  1. Build any kind of form input components. Not just traditional inputs, but anything you want and get that validation for free

  2. Add validation rules and use them with simple syntax

  3. Use handlers for different states of your form. Ex. "onSubmit", "onError", "onValid" etc.

  4. Server validation errors automatically binds to the correct form input component

  1. Download from this REPO and use globally (Formsy) or with requirejs
  2. Install with npm install formsy-react and use with browserify etc.
  3. Install with bower install formsy-react

0.5.2

  • Fixed bug with handlers in ajax requests (Thanks @smokku)

0.5.1

  • Fixed bug with empty validations

0.5.0

  • Added cross input validation
  • Fixed bug where validation rule refers to a string
  • Added "invalidateForm" function when manually submitting the form

0.4.1

  • Fixed bug where form element is required, but no validations

0.4.0:

  • Possibility to handle form data manually using "onSubmit"
  • Added two more default rules. isWords and isSpecialWords

0.3.0:

  • Deprecated everything related to buttons automatically added
  • Added onValid and onInvalid handlers, use those to manipulate submit buttons etc.

Older changes

Formsy gives you a form straight out of the box

  /** @jsx React.DOM */
  var Formsy = require('formsy-react');
  var MyAppForm = React.createClass({
    changeUrl: function () {
      location.href = '/success';
    },
    enableButton: function () {
      this.setState({
        canSubmit: true
      });
    },
    disableButton: function () {
      this.setState({
        canSubmit: false
      });
    },
    render: function () {
      return (
        <Formsy.Form url="/users" onSuccess={this.changeUrl} onValid={this.enableButton} onInvalid={this.disableButton}>
          <MyOwnInput name="email" validations="isEmail" validationError="This is not a valid email" required/>
          <button type="submit" disabled={!this.state.canSubmit}>Submit</button>
        </Formsy.Form>
      );
    }
  });

This code results in a form with a submit button that will POST to /users when clicked. The submit button is disabled as long as the input is empty (required) or the value is not an email (isEmail). On validation error it will show the message: "This is not a valid email".

Building a form element

  /** @jsx React.DOM */
  var Formsy = require('formsy-react');
  var MyOwnInput = React.createClass({

    // Add the Formsy Mixin
    mixins: [Formsy.Mixin],

    // setValue() will set the value of the component, which in 
    // turn will validate it and the rest of the form
    changeValue: function (event) {
      this.setValue(event.currentTarget.value);
    },
    render: function () {

      // Set a specific className based on the validation
      // state of this component. showRequired() is true 
      // when the value is empty and the required prop is 
      // passed to the input. showError() is true when the 
      // value typed is invalid
      var className = this.showRequired() ? 'required' : this.showError() ? 'error' : null;

      // An error message is returned ONLY if the component is invalid
      // or the server has returned an error message
      var errorMessage = this.getErrorMessage();

      return (
        <div className={className}>
          <input type="text" onChange={this.changeValue} value={this.getValue()}/>
          <span>{errorMessage}</span>
        </div>
      );
    }
  });

So this is basically how you build your form elements. As you can see it is very flexible, you just have a small API to help you identify the state of the component and set its value.

Formsy.defaults({
  contentType: 'urlencoded', // default: 'json'
  headers: {} // default headers
  /* DEPRECATED
  hideSubmit: true, // default: false
  submitButtonClass: 'btn btn-success', // default: null
  cancelButtonClass: 'btn btn-default', // default: null
  buttonWrapperClass: 'my-wrapper' // default: null
  */
});

Use defaults to set general settings for all your forms.

<Formsy.Form className="my-class"></Formsy.Form>

Sets a class name on the form itself.

<Formsy.Form url="/users"></Formsy.Form>

Will either POST or PUT to the url specified when submitted. If you do not pass a url the data for the form will be passed to the onSubmit handler.

<Formsy.Form url="/users" method="PUT"></Formsy.Form>

Supports POST (default) and PUT.

<Formsy.Form url="/users" method="PUT" contentType="urlencoded"></Formsy.Form>

Supports json (default) and urlencoded (x-www-form-urlencoded).

Note! Response has to be json.

<Formsy.Form url="/users" onSuccess={this.changeUrl}></Formsy.Form>

Takes a function to run when the server has responded with a success http status code.

<Formsy.Form url="/users" onSubmit={this.showFormLoader}></Formsy.Form>

Takes a function to run when the submit button has been clicked. The first argument is the data of the form. The second argument will reset the form. The third argument will invalidate the form by taking an object that maps to inputs. E.g. {email: "This email is taken"}. Resetting or invalidating the form will cause setState to run on the form element component.

note! When resetting the form the form elements needs to bind its current value using the getValue method. That will empty for example an input.

<Formsy.Form url="/users" onSubmitted={this.hideFormLoader}></Formsy.Form>

Takes a function to run when either a success or error response is received from the server.

<Formsy.Form url="/users" onError={this.changeToFormErrorClass}></Formsy.Form>

Takes a function to run when the server responds with an error http status code.

<Formsy.Form url="/users" onValid={this.enableSubmitButton}></Formsy.Form>

Whenever the form becomes valid the "onValid" handler is called. Use it to change state of buttons or whatever your heart desires.

<Formsy.Form url="/users" onInvalid={this.disableSubmitButton}></Formsy.Form>

Whenever the form becomes invalid the "onInvalid" handler is called. Use it to for example revert "onValid" state.

<MyInputComponent name="email"/>

The name is required to register the form input component in the form.

<MyInputComponent name="email" value="My default value"/>

You should always use the getValue() method inside your formsy form element. To pass a default value, use the value attribute.

<MyInputComponent name="email" validations="isEmail"/>
<MyInputComponent name="number" validations="isNumeric,isLength:5:12"/>

An comma seperated list with validation rules. Take a look at Validators to see default rules. Use ":" to separate arguments passed to the validator. The arguments will go through a JSON.parse converting them into correct JavaScript types. Meaning:

<MyInputComponent name="fruit" validations="isIn:['apple', 'orange']"/>
<MyInputComponent name="car" validations="mapsTo:{'bmw': true, 'vw': true}"/>

Works just fine.

<MyInputComponent name="email" validations="isEmail" validationError="This is not an email"/>

The message that will show when the form input component is invalid.

<MyInputComponent name="email" validations="isEmail" validationError="This is not an email" required/>

A property that tells the form that the form input component value is required.

var MyInput = React.createClass({
  mixins: [Formsy.Mixin],
  render: function () {
    return (
      <input type="text" onChange={this.changeValue} value={this.getValue()}/>
    );
  }
});

Gets the current value of the form input component.

var MyInput = React.createClass({
  changeValue: function (event) {
    this.setValue(event.currentTarget.value);
  },
  render: function () {
    return (
      <input type="text" onChange={this.changeValue} value={this.getValue()}/>
    );
  }
});

Sets the value of your form input component. Notice that it does not have to be a text input. Anything can set a value on the component. Think calendars, checkboxes, autocomplete stuff etc. Running this method will trigger a setState() on the component and do a render.

var MyInput = React.createClass({
  changeValue: function (event) {
    this.setValue(event.currentTarget.value);
  },
  render: function () {
    return (
      <div>
        <input type="text" onChange={this.changeValue} value={this.getValue()}/>
        {this.hasValue() ? 'There is a value here' : 'No value entered yet'}
      </div>
    );
  }
});

The hasValue() method helps you identify if there actually is a value or not. The only invalid value in Formsy is an empty string, "". All other values are valid as they could be something you want to send to the server. F.ex. the number zero (0), or false.

var MyInput = React.createClass({
  changeValue: function (event) {
    this.setValue(event.currentTarget.value);
  },
  render: function () {
    return (
      <div>
        <input type="text" onChange={this.changeValue} value={this.getValue()}/>
        <button onClick={this.resetValue()}>Reset</button>
      </div>
    );
  }
});

Resets to empty value. This will run a setState() on the component and do a render.

var MyInput = React.createClass({
  changeValue: function (event) {
    this.setValue(event.currentTarget.value);
  },
  render: function () {
    return (
      <div>
        <input type="text" onChange={this.changeValue} value={this.getValue()}/>
        <span>{this.getErrorMessage()}</span>
      </div>
    );
  }
});

Will return the server error mapped to the form input component or return the validation message set if the form input component is invalid. If no server error and form input component is valid it returns null.

var MyInput = React.createClass({
  changeValue: function (event) {
    this.setValue(event.currentTarget.value);
  },
  render: function () {
    var face = this.isValid() ? ':-)' : ':-(';
    return (
      <div>
        <span>{face}</span>
        <input type="text" onChange={this.changeValue} value={this.getValue()}/>
        <span>{this.getErrorMessage()}</span>
      </div>
    );
  }
});

Returns the valid state of the form input component.

var MyInput = React.createClass({
  changeValue: function (event) {
    this.setValue(event.currentTarget.value);
  },
  render: function () {
    return (
      <div>
        <span>{this.props.label} {this.isRequired() ? '*' : null}</span>
        <input type="text" onChange={this.changeValue} value={this.getValue()}/>
        <span>{this.getErrorMessage()}</span>
      </div>
    );
  }
});

Returns true if the required property has been passed.

var MyInput = React.createClass({
  changeValue: function (event) {
    this.setValue(event.currentTarget.value);
  },
  render: function () {
    var className = this.showRequired() ? 'required' : '';
    return (
      <div className={className}>
        <input type="text" onChange={this.changeValue} value={this.getValue()}/>
        <span>{this.getErrorMessage()}</span>
      </div>
    );
  }
});

Lets you check if the form input component should indicate if it is a required field. This happens when the form input component value is empty and the required prop has been passed.

var MyInput = React.createClass({
  changeValue: function (event) {
    this.setValue(event.currentTarget.value);
  },
  render: function () {
    var className = this.showRequired() ? 'required' : this.showError() ? 'error' : '';
    return (
      <div className={className}>
        <input type="text" onChange={this.changeValue} value={this.getValue()}/>
        <span>{this.getErrorMessage()}</span>
      </div>
    );
  }
});

Lets you check if the form input component should indicate if there is an error. This happens if there is a form input component value and it is invalid or if a server error is received.

An example:

Formsy.addValidationRule('isFruit', function (value) {
  return ['apple', 'orange', 'pear'].indexOf(value) >= 0;
});
<MyInputComponent name="fruit" validations="'isFruit"/>

Another example:

Formsy.addValidationRule('isIn', function (value, array) {
  return array.indexOf(value) >= 0;
});
<MyInputComponent name="fruit" validations="isIn:['apple', 'orange', 'pear']"/>

Cross input validation:

Formsy.addValidationRule('isMoreThan', function (value, otherField) {
  // The this context points to an object containing the values
  // {childAge: "", parentAge: "5"}
  // otherField argument is from the validations rule ("childAge")
  return Number(value) > Number(this[otherField]);
});
<MyInputComponent name="childAge"/>
<MyInputComponent name="parentAge" validations="isMoreThan:childAge"/>

Validators

isValue

<MyInputComponent name="foo" validations="isValue"/>

Returns true if the value is thruthful

isEmail

<MyInputComponent name="foo" validations="isEmail"/>

Return true if it is an email

isTrue

<MyInputComponent name="foo" validations="isTrue"/>

Returns true if the value is the boolean true

isNumeric

<MyInputComponent name="foo" validations="isNumeric"/>

Returns true if string only contains numbers

isAlpha

<MyInputComponent name="foo" validations="isAlpha"/>

Returns true if string is only letters

isWords

<MyInputComponent name="foo" validations="isWords"/>

Returns true if string is only letters, including spaces and tabs

isSpecialWords

<MyInputComponent name="foo" validations="isSpecialWords"/>

Returns true if string is only letters, including special letters (a-z,ú,ø,æ,å)

isLength:min, isLength:min:max

<MyInputComponent name="foo" validations="isLength:8"/>
<MyInputComponent name="foo" validations="isLength:5:12"/>

Returns true if the value length is the equal or more than minimum and equal or less than maximum, if maximum is passed

equals:value

<MyInputComponent name="foo" validations="equals:4"/>

Return true if the value from input component matches value passed (==).

License

formsy-react is licensed under the MIT license.

The MIT License (MIT)

Copyright (c) 2015 Gloppens EDB Lag

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.