admin管理员组文章数量:1410712
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.
本文标签:
版权声明:本文标题:javascript - How to allow only Decimal values up to 2 decimal places in an input field in React JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744309586a2599966.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论