我想让用户只输入整数或浮点数。现在我只能输入整数,它允许输入点或逗号。无法找到正确的正则表达式来验证整数和浮点数。
<input
type="text"
id="depositedAmount"
maxLength={9}
placeholder="Enter amount"
onChange={(e) => this.handleInputChange(e, currentComProfile)}
value={depositedAmount}
/>
handleInputChange=(e, currentComProfile) => {
const re = /^[+-]?\d+(\.\d+)?$/;
if (e.target.value === '' || re.test(e.target.value)) {
if (e.target.id === 'depositedAmount') {
this.props.updateDepositedAmount(e.target.value, currentComProfile);
}
if (e.target.id === 'willBeCreditedAmount') {
this.props.updateWillBeCreditedAmount(e.target.value, currentComProfile);
}
}
}
您可以使用
const rx_live = /^[+-]?\d*(?:[.,]\d*)?$/;
用于实时验证。对于最终验证,使用
const rx_final = /^[+-]?\d+(?:[.,]\d+)?$/;
或者,更好的是,只需使用正则表达式pattern
属性:pattern="[+-]?\d*(?:[.,]\d*)?"
.
NOTE
-
^
- 字符串的开头
-
[+-]?
- 可选的+
or -
-
\d*
- 0个或多个数字
-
(?:[.,]\d*)?
- 可选序列.
or ,
然后是 0 个或多个数字
-
$
- 字符串末尾。
在最终验证中,\d+
被用来代替\d*
匹配一个或多个数字而不是零个或多个 digits.
请参阅 JS 演示:
const rx_live = /^[+-]?\d*(?:[.,]\d*)?$/;
class TestForm extends React.Component {
constructor() {
super();
this.state = {
depositedAmount: ''
};
}
handleDepositeAmountChange = (evt) => {
if (rx_live.test(evt.target.value))
this.setState({ depositedAmount : evt.target.value });
}
render() {
return (
<form>
<input
type="text"
id="depositedAmount"
maxLength={9}
pattern="[+-]?\d+(?:[.,]\d+)?"
placeholder="Enter amount"
onChange={this.handleDepositeAmountChange}
value={this.state.depositedAmount}
/>
</form>
)
}
}
ReactDOM.render( < TestForm /> , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)