I'm trying to use the IMaskInput
component from react-imask@6.0.7
and I want to restrict the input of negative numbers. While there are a few ways I can do this (such as setting the min=0
or always returning the absolute value of any input) I understand that there is a prop where you can define if signed numbers (aka the signed
prop) can be allowed or not. Does anyone know how this should properly be used? Here is an example of my IMaskInput
component:
import { IMaskInput } from "react-imask";
function MyComponent(props) {
const [value, setValue] = useState(undefined);
return (
<IMaskInput
className={props.className}
data-testid={props.testId}
id={props.fieldId}
mapToRadix={["."]}
mask={Number}
max={props.max}
min={props.min}
padFractionalZeros={true}
radix={"."}
scale={2}
signed={props.signed}
thousandsSeparator={","}
unmask={true}
value={value !== undefined && value !== null && !Number.isNaN(value) ? value.toString() : ""}
onAccept={(value: string) => {
const newValue: number | undefined = parseFloat(value);
setValue(newValue)
}}
{...props}
/>
)
}
const myProps = {
min: -(10**8),
max: 10**8,
fieldId: "value",
testId: "value-test-id",
signed: false, // This one should prevent the input of the "-" sign
}
So, the problem I was encountering is that the min
and signed
props conflict. The min
prop will always take precedence over the signed
prop. If min >= 0
or min=undefined
then the signed
prop's value will be effective. If signed=false
and min < 0
then your signed
prop will be ignored and signed values (adding '-' or '+' before a number) will be allowed.
It's also worth noting that signed
prop was removed on react-imask@7.0.0
, so you should just use the min
prop if you are on any version after that one.