react-validated-component

0.0.4 • Public • Published

react-validated-component

Usage

import { createValidatedComponent } from 'react-validated-component'
 
...
 
// Dummy react component
class priceInput extends React.Component {
  constructor(props) {
    super(props)
 
    this.setStateAndValidate = this.setStateAndValidate.bind(this)
  }
 
  setStateAndValidate(state) {
    let keyToValidate = Object.keys(state)[0]
 
    // Calls the validate method from react-validated-component
    this.props.validate(keyToValidate, state[keyToValidate], this.state)
 
    this.setState({
      [keyToValidate]: state[keyToValidate]
    })
  }
 
  render() {
    // this.props.isValid contains the valid state of the input (injected through react-validated-component)
    return <input onChange={(ev) => this.setStateAndValidate({ price: ev.target.value })} /> 
  }
}
 
const ValidatedComponent = createValidatedComponent(priceInput)
 
const validators = {
  price: { name: 'presence' } // This automatically checks for not empty input,
  phoneNumber: [
    { name: 'presence' },
    { 
      name: 'length', 
      maxLength: 9, 
      disabled: (key, value, state) => { 
        if (state.isValidating) {
          return false
        }
 
        return true
      }  
    }, // Also an included validator
    { validate: (value, key, state) => { /* define a custom validation inside */ } } 
  ]
}
 
// Now we can use ValidatedComponent like this:
// <ValidatedComponent validators={validators} />
// Or through react-redux's connect
// Example:
 
// and returning validators as a prop in mapStateToProps
const mapStateToProps = () => ({ validators })
 
connect(mapStateToProps)(createValidatedComponent(priceInput))

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 0.0.4
    0
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 0.0.4
    0
  • 0.0.3
    0
  • 0.0.2
    0
  • 0.0.1
    0

Package Sidebar

Install

npm i react-validated-component

Weekly Downloads

0

Version

0.0.4

License

ISC

Unpacked Size

124 kB

Total Files

14

Last publish

Collaborators

  • asantos00
  • jsaguiar