I have created a currency input React component to allow the user to enter numeric values. I made the input type to "number". This only works in Chrome (user can still enter non-numeric values in Firefox).
CurrencyInput Component:
import React from "react";
import { Form } from "semantic-ui-react";
interface ICurrencyInputProps {
onChange(value: any): void;
checkRange?: boolean;
min: number;
max: number;
validationMessage: string;
cssClasses?: string;
}
export class CurrencyInput extends React.Component<ICurrencyInputProps> {
state = {
showInvalidError: false,
value: null
};
render() {
return (
<>
<Form.Input
icon="pound"
iconPosition="left"
placeholder="Whole pounds"
className={this.props.cssClasses}
type="text"
error={this.state.showInvalidError}
onChange={(event: any) => {
let value = null;
if (event.target.value) value = parseInt(event.target.value);
this.setState({ value: value });
this.props.onChange(value);
}}
/>
</>
);
}
}
export default CurrencyInput;
Usage:
<CurrencyInput
cssClasses="has_tooltip"
checkRange={true}
onChange={(data: any) => {
this.setState({
premium: data
});
}}
min={TargetPremiumRange.MIN}
max={TargetPremiumRange.MAX}
validationMessage="Validation message"/>
I want to prevent the user from entering any non-numeric value. How can I achieve this?
You can change the error state in your onChange in <Form.Input>
. Something like:
onChange={(event: any) => {
let value = null;
if (event.target.value) {
value = parseInt(event.target.value, 10);
// Test for valid number
if (isNaN(value)) {
setState({showInvalidError: true});
} else {
this.setState({ value: value });
this.props.onChange(value);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With