Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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, ...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