UNPKG

react-form-validator-components

Version:

Components for react-form-validator-core

120 lines (107 loc) 3.02 kB
### Installation ``` npm i react-form-validator-components --save-dev yarn add react-form-validator-components --save ``` ### Components Utilizes [@material-ui](https://material-ui.com/) and [@material-ui/pickers](https://material-ui-pickers.dev/getting-started/installation) under the hood Implementation of several components based off of [react-form-validator-core](https://www.npmjs.com/package/react-form-validator-core) To use with ValidatorForm ``` ... import { ValidatorForm, TextValidator } from 'react-form-validator-components' ... render() { return ( <ValidatorForm ref={r => (this.form = r)} onSubmit={this.handleSubmit}> <TextValidator name="name" value={this.props.name} validators={['required']} errorMessages="Name is required" /> </ValidatorForm> ); } ``` To use with onBlur just pass the onBlur prop ``` render() { return ( <ValidatorForm ref={r => (this.form = r)} onSubmit={this.handleSubmit}> <TextValidator name="name" value={this.props.name} onChange={handle individual changes to state here} onBlur={handle submission here} /> </ValidatorForm> ); } ``` ##### TextValidator (TextField) Example with default value ``` <TextValidator label="Text" value={props.value} defaultValue={''} /> ``` ##### SelectValidator (Select) Example with default value based on data in state and a label. A label requires inputProps id definitiion. ``` <SelectValidator label="Select Example" value={props.value} defaultValue={state.data[0].id} inputProps={{ id: 'select-example' }} > {this.props.children} </SelectValidator> ``` ##### DateValidator (DatePicker) Example with default value ``` constructor(props) { super(props); this.state = { defaultValue: moment().format('YYYY-MM-DD') } } ... <DateValidator value={props.value} defaultValue={state.defaultValue} /> ``` ### Usage To use DateValidator ``` import MomentUtils from '@date-io/moment'; import { MuiPickerUtilsProvider } from 'react-form-validator-components' function App() { return ( <MuiPickerUtilsProvider utils={MomentUtils} locale="en"> <Root /> </MuiPickerUtilsProvider> ); } ``` To provide a default value that will call onChange immediately if the value is false ``` <TextValidator value={null} defaultValue={'Text'} onChange={val => this.onChange(val)} /> ``` This can be helpful in the case where the TextValidator is part of something such as [Material Table](https://material-table.com/#/docs/get-started). The editComponent holds its own value for the data, and is only updated onChange. So even if you provide an alternative to the TextValidator through ``` <TextValidator value={editProps.value || ''} /> ``` The data held by Material Table will not be updated, then when you go to "submit" through Material Table, it will still show an invalid default value. Providing a defaultValue passes back the value immediately.