javascript - 如何使用正则表达式进行正确的输入验证?
问题描述
我想让用户只输入整数或浮点数。现在我只能输入整数,它允许输入点或逗号。找不到合适的正则表达式来验证整数和浮点数。
<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*)?
.
- 一个可选的or序列,,
然后是 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>
推荐阅读
- mysql - 根据另一列的最大值选择每列值之一
- java - HttpUrlConnection“PUT”请求也发送“GET”请求
- reactjs - 错误:spawn /Applications/GitHub Desktop.app/Contents/Resources/app/git/bin/git ENOENT
- wso2 - wso2ei 集成器是无状态的吗?(在集群环境中)
- c# - 由于“'MYAPPLICATION.ServiceFabricPkg'已更改”而无法升级 Service Fabric 服务,即使它没有更改
- google-analytics - Google Analytics(分析)自定义维度未报告
- python - TypeError:“str”对象不可调用 Python 3 Ubuntu
- jenkins - 清理 Jenkins 工作区时排除以特定表达式开头的文件
- node.js - 无法安装 node-sass
- java - 通过意图在选项卡式活动中编辑 TextView - Android