UNPKG

react-form-validator-components

Version:

Components for react-form-validator-core

112 lines (96 loc) 2.34 kB
import React from 'react'; import PropTypes from 'prop-types'; import {ValidatorComponent} from 'react-form-validator-core'; import Select from '@material-ui/core/Select'; import red from '@material-ui/core/colors/red'; import InputLabel from '@material-ui/core/InputLabel'; const style = { right: 0, fontSize: '12px', color: red[300], position: 'absolute', marginTop: '-25px', }; class SelectValidatorCore extends ValidatorComponent { componentDidMount() { super.componentDidMount(); if (this.props.doInitialValidation) { this.validate(this.props.value, true); } } onChange(event) { if (this.props.onChange) { this.props.onChange(event.target.value); } } render() { const { error, errorMessages, validators, requiredError, helperText, validatorListener, withRequiredValidator, //custom onChange, doInitialValidation, children, label, InputLabelProps, inputProps, ...rest } = this.props; const { isValid } = this.state; return ( <div> {label && inputProps && inputProps.id && InputLabelProps && ( <InputLabel {...InputLabelProps}>{label}</InputLabel> )} <Select {...rest} onChange={this.onChange.bind(this)} inputProps={inputProps} error={!isValid || error}> {children} </Select> {this.errorText()} </div> ); } errorText() { const {isValid} = this.state; if (isValid) { return null; } return <div style={style}>{this.getErrorMessage()}</div>; } } SelectValidatorCore.propTypes = { // ValidatorComponent errorMessages: PropTypes.oneOfType([ PropTypes.array, PropTypes.string ]), validators: PropTypes.array, value: PropTypes.any, validatorListener: PropTypes.func, withRequiredValidator: PropTypes.bool, // Custom doInitialValidation: PropTypes.bool, children: PropTypes.oneOfType([ PropTypes.array, PropTypes.object ]), label: PropTypes.string }; SelectValidatorCore.defaultProps = { // ValidatorComponent errorMessages: 'error', validators: [], validatorListener: () => {}, // Custom doInitialValidation: false, children: {} }; export default SelectValidatorCore;