I need an input in React that only write able -99 to 99 is there a way to achieve this?
i’ve tried on key down, but it brokes when you try to write double dashes for example;
it works perfectly when you try to write -45 or something.but when you add double dashes then it brokes it becomes writeable anything for example –9909349
also in this function i can write but i shouldn’t: 1-9034- etc.
only acceptable: -99 to 99
code:
const validateInput = (e) => {
const currentValue = e.target.value
const newValue = currentValue + e.key
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft' || e.key === 'Backspace') {
return
}
if (e.key === '-' && currentValue === '') {
return
}
if (newValue.replace(/0/g, '').length === 0) {
e.preventDefault()
return
}
if (parseInt(newValue) >= -99 && parseInt(newValue) <= 99) {
return
}
e.preventDefault()
}
2
Answers
The
min
andmax
attributes in the<input>
tag with type="number" are used to set the range of acceptable values, but they don’t prevent the user from manually entering values outside that range.You can use this logic to restrict the value between -99 to 99.
Or you can validate
onblur
for better UX. It will validate the input and reset it to the nearest valid value only after the user has finished editingIn a React application, you can create a component that allows users to input values between -99 and 99 and validate their input. Here’s an example of how to create a simple React component to achieve this: