6

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?

3
  • type="text" pattern="[0-9]*"cheers Commented Feb 4, 2020 at 20:34
  • Tried that too. Did'nt work. Commented Feb 4, 2020 at 20:48
  • Even if the user can enter the text, when the button is clicked, there would be a warning, which will prevent the user from entering non-numeric values.[in firefox browser] Commented Dec 29, 2020 at 2:12

2 Answers 2

5
<Input
onKeyPress={(event) => {
        if (!/[0-9]/.test(event.key)) {
          event.preventDefault();
        }
      }}
/>
Sign up to request clarification or add additional context in comments.

2 Comments

Please explain your code and also state why your solution should be preferred over the other answers.
I've tried other solutions on StackOverflow by far this is the only answer that works for me. Thank you.
4

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);
        }
    }       
}  

2 Comments

Thanks. But the user still will be able to enter non numeric values?
Yes, but if the value is incorrect, it will not change the value saved in the state, your error state will be displayed, and the user will be allowed to correct it. You could check on each keydown() and prevent anything from a number being typed, but that doesn't solve for the case where someone just pastes in a value. onchange() should cover that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.