Created
May 3, 2021 20:00
-
-
Save steve-codemunkies/b3d193a404b08f6aa4b19cf65be73f2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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