Jishun / react-validated-input

Instance based validated input component for react
MIT License
12 stars 1 forks source link

react-validated-input

Why -- Why another input component?

Built in types

Installation

npm install react-validated-input --save

Or You can also use the standalone build by including dist/react-validated-input.js in your page. If you use this, make sure you have already included React, and it is available as a global variable.

Usage

//import
import Input, * as inputHelper from 'react-validated-input'

//to render
render(){
  return <Input type="text" validate={this.state.validation} instance={this.state.user} propertyKey="email" rules={{presence: true, email: true}} placeholder="Email Address" label="Email"></Input>
}
//to validate, triggered by some button click, or certain onChange events
doValidate(){
  //if there is only one validation group, pass the defaults like this inputHelper.validate(this, [this.state.user])
  //otherwise pass the validation group name(which is the property name in t he state other than 'validation'):  inputHelper.validate(this, [this.state.user], null, 'validateContent')
  //The null above is an optional result collection, pass an empty object if you don't want your state instance to be changed
  //Support multiple group validations, pass the 4th param as an array of strings instead of a single string will do the job: as below
  inputHelper.validate(this, [this.state.user], null, ['validation', 'validateContent'])
    .then(
        () => {
          //do something when no errors
        },
        (errorMessage) => {
          //do something with the error message
        }
      )
      .catch((err) => console.log(err))
}

Global Configuration


import DatePicker from 'react-datepicker'
import moment from 'moment'
import * as inputHelper from 'react-validated-input'
import validator from 'validate.js'

inputHelper.config({
  validationStateProperty: 'validation', // the property name in the state object to link the validation
  useWraper: true, // uses wrappers for the input, built in wrappers are bootStrap styles
  errorCssClass : 'has-error', // the class applied when has error
  wraningCssClass : 'has-warning', // the class applied when has warning
  successCssClass : 'has-success', // the class applied when has success
  feedbackCssClass : 'has-feedback', // the class applied when has feedback
  propsPassThrough : true, // default to true, pass every props to the internal components
  mutate : false, // default to false, not allow instance to be changed by this component, set to true it will put the error indicator into the instance when validation failed,
  errorIndicatorKey : '_hasError', //the property name of the error indicator put in to the instance when mutate = true
  errorMessageKey : '_errors', //the property name of the error message collection put in to the instance when mutate = true
  classNameKey : '_class', // the property name used to find the validation className
  rulesKey : '_rules' // the property name used to find the validation rules
})

//to validate an instance of an payment method entry, here we name the class of instance as 'payMethod', the rules for the members are set this way.
inputHelper.registerClasses({
  payMethod: {
    cardNumber: {
      presence: true,
      format: {
        pattern: /^(34|37|4|5[1-5]).*$/,
        message: function(value, attribute, validatorOptions, attributes, globalOptions) {
          return validator.format("^%{num} is not a valid credit card number", {
            num: value
          });
        }
      },
    },
    name: {presence: true},
    expiration: {presence: true}
  }})

Extending the types

Below code shows how to extend an input type 'datepicker' with the existing react-datepicker component

import DatePicker from 'react-datepicker'
import moment from 'moment'
import * as inputHelper from 'react-validated-input'

inputHelper.extend('datepicker', {
    wrapper: 'div', //the wrapper component to wrap the component, this will wrap this datepicker with bootstrap style, set to null to disable wrapping.
    wrapperClass: 'form-group',  // the className to put into the wrapper
    className: 'form-control', //the className to put into the component
    component: DatePicker, //the component reference, react class or string such as 'input'
    valueProp: 'selected', // the prop name used to assign value to the component, this date picker uses 'selected' instead of 'value'
    defaultProps: { dateFormat: 'MM/DD/YYYY' }, // the default props that the component needs
    getValueOnChange: (e, props) => e.toString(), // to internally handle the event in onChange, otherwise it will try to retrieve e.target.value
    includedLabel : false, // indicates the component does not include a label props it self, we'll renderer the label for it
    setValue: (value, props) => isNaN(Date.parse(value))? null:moment(value), //the handler to pass the value from instance to the component
    propsMap: [{from: 'placeholder', to: 'placeholderText'}] //map a different name for the default properties
})

Properties

API

Managing Rules:

Extending validator

Build

  npm install
  make js

Contribute?

----- Working in Progress -----