admin管理员组

文章数量:1194744

I want to restrict users from entering negative values. I am using min = "0". With this i can restrict users from decrementing to 0, i.e, users can only decrement value till 0. But they are able to type "-". How to prevent in react js.

=/src/index.js

<input
   type="number"
   min="0"
   step="1"                        
   onChange={this.handleChange}                        
   className="w-100"
   value= "1"
   />

I want to restrict users from entering negative values. I am using min = "0". With this i can restrict users from decrementing to 0, i.e, users can only decrement value till 0. But they are able to type "-". How to prevent in react js.

https://codesandbox.io/s/react-input-example-forked-xnvxm?file=/src/index.js

<input
   type="number"
   min="0"
   step="1"                        
   onChange={this.handleChange}                        
   className="w-100"
   value= "1"
   />
Share Improve this question edited Sep 16, 2024 at 18:48 VLAZ 29k9 gold badges62 silver badges82 bronze badges asked Mar 16, 2021 at 5:36 theWanderertheWanderer 6362 gold badges13 silver badges33 bronze badges 5
  • Are you trying to make it a controlled input? Meaning its value will be set through a state variable? That also means you re-render it every time you make a change to it. – codemonkey Commented Mar 16, 2021 at 5:41
  • how about: if (value < 0) { return -value } ? – lam Commented Mar 16, 2021 at 5:42
  • @codemonkey Yes... – theWanderer Commented Mar 16, 2021 at 5:43
  • value={Math.max(0, this.state.inputValue)} or do a similar calculation in handleChange. – Drew Reese Commented Mar 16, 2021 at 5:43
  • Can you once take a look at this: https://stackoverflow.com/questions/19233415/how-to-make-type-number-to-positive-numbers-only/19233458 – Amee Bhadania Commented Mar 16, 2021 at 5:58
Add a comment  | 

9 Answers 9

Reset to default 10

You can add an onKeyPress listener to the input element and that will be triggered before the onChange and call a function that will prevent default behaviour when the minus button is pressed.

const preventMinus = (e) => {
    if (e.code === 'Minus') {
        e.preventDefault();
    }
};

<input               
  type="number"
  min="0"
  onKeyPress={preventMinus}
/>

Note that this will still allow negative values to be pasted into the input. For this, you can add an onPaste listener and check the clipboard data to see if it's negative and prevent the default behaviour.

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

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

<input               
  type="number"
  min="0"
  onPaste={preventPasteNegative}
  onKeyPress={preventMinus}
/>

Handling Empty Input & Negative Numbers

// Converting App into Class-Component
class App extends React.Component {
  // Set State
  constructor(props) {
    super(props);
    this.state = {
      number: ""
    };
  }

  render() {
    return (
      <div className="App">
        <input
          type="number"
          min="0"
          step="1"
          onChange={(e) => {
            let val = parseInt(e.target.value, 10);
            if (isNaN(val)) {
              this.setState({ number: "" });
            } else {
              // is A Number
              val = val >= 0 ? val : 0;
              this.setState({ number: val });
            }
          }}
          className="w-100"
          // Assign State
          value={this.state.number}
        />
      </div>
    );
  }
}

Use some local component state to hold the input's value and use Math.max(0, value) to ensure the value prop/attribute is a non-negative value. The input's value will be a string in the onChange handler so remember to coerce it back to a number value for state.

function App() {
  const [value, setValue] = React.useState(0);
  return (
    <div className="App">
      <label>
        Try entering a negative value
        <input
          type="number"
          min="0"
          step="1"
          className="w-100"
          value={value && Math.max(0, value)}
          onChange={e => setValue(e.target.value ? Number(e.target.value) : e.target.value)}
        />
      </label>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

You can use a regex to validate the input before setting the state of your input and sync the input value with your state value.


<input
  type="number"                  
  onChange={this.handleChange}                        
  className="w-100"
  value= {this.state.inputVal}
/>

validateNumber = (value) => {
  //true for digits only.
  const regex = /^[0-9]+$/
  return regex.test(value);
}
handleChange = ({target}) => {
  const {name,value} = target;
  const {inputVal} = this.state;

  if(value === '') {
    return this.setState({inputVal:''});
  }

  if(this.validateNumber(value)) {
    this.setState({inputVal:value})
  } else {
    this.setState({inputVal:inputVal})
  }
}

<input type="number" onKeyDown={preventNegativeValues}/>

//function export

export const preventNegativeValues = (e) => ["e", "E", "+", "-"].includes(e.key) && e.preventDefault()

You can filter out input value inside handlechange. Something like this:

const App = () => {
  const [value, setValue] = useState("");

  const handleChange = (e) => {
    if (!isNaN(e.target.value)) {
      setValue(e.target.value);
    }
  };
  return (
    <div className="App">
      <input
        type="text"
        value={value}
        onChange={handleChange}
        className="w-100"
      />
    </div>
  );
};

Here is the demo: https://codesandbox.io/s/react-input-example-forked-kr2xc?file=/src/index.js

Other solutions weren't working for me (I could input negative number from scrolling mouse wheel or trackpad), so I made a kind of hardcoded method:

onChange={function (event) {
  if (value > 0 || event.target.valueAsNumber >= 0) {
    setValue(event.target.valueAsNumber);
  }
}}

I prefer this answer as it has alot of functionality in one.
Use Math.sign() it has the following possible results:
it returns 1 if the argument is positive.
it returns -1 if the argument is negative
it returns 0 if the argument is 0
it returns -0 if the argument is -0
in all other cases it returns NaN (not a number)
example
if(Math.sign(somevalue)!=1){ console.log("please provide a valid number" } }

Use this for latest react version in input field as number

 <input
 type="number"      
 min={0}
 step={1}
 onKeyDown={(e) => {
 if (e.code === 'Minus') {
    e.preventDefault();
    }
  }}
 />

本文标签: javascriptHow to prevent user from entering negative number in reactStack Overflow