DadyByte
DadyByte

Reputation: 914

Allow only numbers in Input in React (antd styling)

I know type=number works but that is not what i want. my HTML:

<FormItem style={{ display: "inline-block" }}>
    {getFieldDecorator('matchPercentage', {
        initialValue: this.state.matchPercentage
     })( 
        <Input type="number" value={this.state.matchPercentage} onChange={this.handlePercentMatch} style={{ width: 100, marginLeft: 10 }} />
     )}
</FormItem>

my Function:

handlePercentMatch = (e) => {
    const isInteger = /^[0-9]+$/;
    if (e.target.value === '' || isInteger.test(e.target.value)) {
      this.setState({ matchPercentage: e.target.value })
    }
  }

My isInteger.test() is working meaning I am able to get only integers in matchPercentage in state. But the problem is It is not reflecting in GUI. I am still able to type alphabets even though they are not being set into state.

I know type="number" works but that is not what i want. I want to validate using react as i want control decimals and upto how many digits and non negative

I have added my code here https://codepen.io/DadyByte/pen/xYgLvy?editors=1010

I found the root cause. If you use FormItem you will be allowed to type no matter what. If I use Input outside FormItem my code is working. What can I do to prevent it

Upvotes: 9

Views: 60986

Answers (7)

Soheil Bakhtyari
Soheil Bakhtyari

Reputation: 210

Just use the code below and it would just accept the numbers, also it works for ant design Input component.

<input
    onKeyPress={(event) => {
        if (!/[0-9]/.test(event.key)) {
            event.preventDefault();
        }
    }}
/>

Upvotes: 8

DSDmark
DSDmark

Reputation: 1261

Hi @DadyByte,

Set the pattern attribute to prevent the user from entering non-integer values in the input field.

<input type="text" pattern="\d*" value={this.state.matchPercentage} onChange={this.handlePercentMatch} style={{ width: 100, marginLeft: 10 }} />

The expression \d* matches any number of digits (0 or more). This will allow only integer values to be entered into the input field.

Alternatively, you could also use /^[0-9]+$/.

handlePercentMatch = (e) => {
  const isInteger = /^[0-9]+$/;
  if (e.target.value === '' || isInteger.test(e.target.value)) {
    this.setState({ matchPercentage: e.target.value }, () => {
      e.target.setSelectionRange(e.target.value.length, e.target.value.length);
    });
  }
}

Upvotes: 0

herlarby
herlarby

Reputation: 111

Ant Design has an InputNumber Component. You could use something like this

import {InputNumber} from 'antd';

Usage

<InputNumber placeholder="Age (Max Age :100,  Min Age:1)" size={'large'} min={1} max={100} onChange={this.handleAgeChange} />

Then your handleAgeChange Functionality could look like

 handleAgeChange = (value) => {
    this.setState((prevState) => (
         { ...prevState, age:value }
    ));
};

Upvotes: 6

Sulung Nugroho
Sulung Nugroho

Reputation: 1683

The simplest and far from complicated way according to www.w3schools.com :

onHandleChangeNumeric = e => {
 let valu = e.target.value;

 if (!Number(valu)) {
 return;
 }

 this.setState({ [e.target.name]: valu });
};

On render input :

 <input
   type="text"
   className="form-control"
   name="someName"
   value={this.state.someName}
   onChange={this.onHandleChangeNumeric}
    />

Impoertant : Do not make type="number", it won't work.

Upvotes: 5

Hadnazzar
Hadnazzar

Reputation: 1616

I assume you use that for telephone number input.

So here is the input you can use.

<input
   placeholder="Telephone Number"
   onChange={ (e) => {
     const telNo = e.target.value;
     const re = /^[0-9\b]+$/;
     if (telNo === '' || re.test(telNo)) {
       this.setState({ telNo: e.target.value });
     }
   }
   value={ this.state.telNo }
   type="tel"
 />

Upvotes: 2

Max Millington
Max Millington

Reputation: 4488

HTML 5 has a native solution:

<input type="number">

This is assuming your Input component is using the HTML5 <input /> tag

Upvotes: 1

Muneeb
Muneeb

Reputation: 1549

Well, it's quite simple just pass type = number to your input field<input value={this.state.matchPercentage} onChange={this.handlePercentMatch} type="number">

Upvotes: 0

Related Questions