Created
May 3, 2021 19:50
-
-
Save steve-codemunkies/95fa4db42b6ae6f91fd01d2ac4e86297 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, ...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