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
|
9 Answers
Reset to default 10You 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
版权声明:本文标题:javascript - How to prevent user from entering negative number in react? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738446257a2087230.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
value={Math.max(0, this.state.inputValue)}
or do a similar calculation inhandleChange
. – Drew Reese Commented Mar 16, 2021 at 5:43