Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only number in Semantic UI React Form Input

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?

like image 248
Joshua Avatar asked Feb 04 '20 20:02

Joshua


1 Answers

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);
        }
    }       
}  
like image 168
Ed Lucas Avatar answered Sep 28 '22 01:09

Ed Lucas