'How to block negative values in Input tags while entering in forms

I am new to React, In my project I have a form with two Input tags, first Input tag is Room number and second Input tag is Amount, What I am trying to achieve is When someone try to enter negative values like -10 or -200 then I have to block those values even it should not appear in Input tags.

Second one is I have to block these kind of values also like 1.2, 3.3, -3.3 even I have to block these values as well it should not appear in Input tags

so someone please help me to achieve this.

This is App.js

import React, { useState } from "react";
import "./App.css";

const App = () => {

  const [data, setData] = useState({})

  const handleChange = ({ target }) => {
    const { name, value } = target
    // console.log(name, value)
    const newData = Object.assign({}, data, {[name]:value})
    setData(newData)
  }

  const validations = () => {
    if(data.room_no && data.amount < 1) {
      alert()
    }
  }


  const handleSubmit = (e) => {
    e.preventDefault()
    console.log(data)
    validations()
  }


  return (
    <div className='container'>
      <div className='row justify-content-center'>
        <div className='col-4'>
          <form onSubmit={handleSubmit}>
            <div className="form-group">
              <label htmlFor="exampleInputEmail1">Room No</label>
              <input name="room_no" onChange={handleChange} type="number" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter room no" />
            </div>
            <div className="form-group">
              <label htmlFor="exampleInputPassword1">AMount</label>
              <input name="amount" onChange={handleChange} type="number" className="form-control" id="exampleInputPassword1" placeholder="AMount" />
            </div>
            <button  type="submit" className="btn btn-primary mt-3">Submit</button>
          </form>
        </div>
      </div>
    </div>
  )
}

export default App


Solution 1:[1]

Our conditions are:

  • Positive Numbers
  • Integers only (non-decimals)

We should handle:

  • Mouse events
  • Keyboard events

For mouse events, we will cover it with input API as normal HTML element, by using min={0} and step={1}.

For keyboard events, the trick is to prevent press event on invalid input.

So we will try and rewrite this plain HTML as React DOM element:

<input type="number" onkeypress="return event.charCode >= 48" min="0" step="1" />
export default function App() {
  return (
    <input
      type="number"
      min={0}
      step={1}
      onKeyPress={(event) => {
        if (event.charCode < 48) {
          event.preventDefault();
        }
      }}
    />
  );
}

Edit adoring-swanson-j5k59

Solution 2:[2]

To block user from entering or pasting the negative values into an input field in react.

add an onKeyPress listener to the input element and call a function that will prevent default behaviour when the minus button is pressed.

To prevent user from pasting the negative values into the input field. Add an onPaste listenerto your input field and to check the clipboard data to see if it's negative and prevent pasting the negative values into the input field.

const preventPasteNegative = (e) => {
    const clipboardData = e.clipboardData || window.clipboardData;
    const pastedData = parseFloat(clipboardData.getData('text'));

    if (pastedData < 0) {
        e.preventDefault();
    }
};

const preventMinus = (e) => {
    if (e.code === 'Minus') {
        e.preventDefault();
    }
};
<input               
  type="number"
  min="0"
  onPaste={preventPasteNegative}
  onKeyPress={preventMinus}
/>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 JustAG33K