0.0.4 • Published 6 years ago

react-validated-component v0.0.4

Weekly downloads
6
License
ISC
Repository
github
Last release
6 years ago

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))
0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

7 years ago

0.0.1

7 years ago