Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steve-codemunkies/b3d193a404b08f6aa4b19cf65be73f2e to your computer and use it in GitHub Desktop.
Save steve-codemunkies/b3d193a404b08f6aa4b19cf65be73f2e to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export const withProbabilityInputValidation = (WrappedComponent) => {
class ProbabilityInputValidation extends Component {
constructor(props) {
super(props);
this.state = {
isValid: true
};
}
valueChanged = (event) => {
const input = event.target.value.trim();
const parsedValue = Number.parseFloat(input);
if(Number.isNaN(parsedValue) || parsedValue < 0 || parsedValue > 1) {
this.setState({ isValid: false });
if(this.props.onValueChanged) this.props.onValueChanged(false, event.target.value);
return;
}
this.setState({ isValid: true });
if(this.props.onValueChanged) this.props.onValueChanged(true, input);
}
render() {
const { error, onChange, onValueChanged, ...finalProps } = this.props;
return <WrappedComponent
{...finalProps}
onChange={this.valueChanged}
error={!this.state.isValid}
/>;
}
}
ProbabilityInputValidation.propTypes = {
onValueChanged: PropTypes.func
};
return ProbabilityInputValidation;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment