Inside a class method, this refers to the React element (which is an instance of this Input React component type). Therefore, we can define a method called validate that will validate the user input and update the state:
<script type="text/babel">
const validator = {
email: (email) => /\S+@\S+\.\S+/.test(email),
password: (password) => password.length > 11 && password.length < 48
}
class Input extends React.Component {
constructor() { ... }
validate = (event) => {
const value = event.target.value;
const valid = validator[this.props.type](value);
this.setState({ value, valid });
}
render() {
return <label>{this.props.label}<input type={this.props.type} onChange={this.validate} /></label>
}
}
...
</script>
The validate method gets the value of the input box from event.target.value, and then uses an external validator object to actually validate the value. The validator method would return true if the value is valid, or false if it is not.
Lastly, the validate method updates the state using the setState method, which is available for all class components.