我想让用户只输入整数或 float 。现在我只能输入整数,它允许输入点或逗号。找不到合适的正则表达式来验证整数和 float 。
<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*)?"
。
注意
^
- 字符串的开始[+-]?
- 可选的+
或-
\d*
- 0 位或更多位(?:[.,]\d*)?
-.
或,
的可选序列,然后是 0 个或多个数字$
- 字符串结尾。
在最终验证中,使用 \d+
而不是 \d*
来匹配一个或多个 数字而不是零或更多 位。
查看 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>
关于javascript - 如何使用正则表达式进行正确的输入验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425087/