I have an Input field to which I want user to be able to enter only number/decimal values up to 2 decimal places. User should not be able to enter any alphabet. Can someone please help me with this
My React Component:
import React from 'react'
import { useState } from "react";
function LoanCalc() {
const [amount, setAmount] = useState();
const handleChange = (event) => {
}
return (
<div className="Container">
<div className="LoanAmount">
<label>Loan Amount:</label>
<span>$
<input type="text" min="4000" max="100000" value={amount} onChange={handleChange}/>
</span>
</div>
</div>
);
}
export default LoanCalc
I have an Input field to which I want user to be able to enter only number/decimal values up to 2 decimal places. User should not be able to enter any alphabet. Can someone please help me with this
My React Component:
import React from 'react'
import { useState } from "react";
function LoanCalc() {
const [amount, setAmount] = useState();
const handleChange = (event) => {
}
return (
<div className="Container">
<div className="LoanAmount">
<label>Loan Amount:</label>
<span>$
<input type="text" min="4000" max="100000" value={amount} onChange={handleChange}/>
</span>
</div>
</div>
);
}
export default LoanCalc
Share
Improve this question
asked Mar 10, 2022 at 15:48
Red CloudRed Cloud
1294 silver badges13 bronze badges
1 Answer
Reset to default 4I've created a code example on codepen.io, too. This is the link to codepen
https://codepen.io/dns_nx/pen/mdxZPaL
In my example, you can only enter up to 2 decimal values. It does not matter, if you use ,
or .
as splitter for the decimals.
This is the code:
import React from 'react'
import { useState } from "react";
function MyComponent(props) {
const [currentValue, setCurrentValue] = useState(undefined);
function checkValue(event) {
setCurrentValue(handleDecimalsOnValue(event.target.value));
}
function handleDecimalsOnValue(value) {
const regex = /([0-9]*[\.|\,]{0,1}[0-9]{0,2})/s;
return value.match(regex)[0];
}
return (
<div>
<input
type="text"
value={currentValue}
onChange={(event) => checkValue(event, 'change')}
/>
</div>
);
}
I did an update on the code above. Now using a regex expression to validate the input instead of splitting the string.