【问题标题】:How to make proper Input validation with regex?如何使用正则表达式进行正确的输入验证?
【发布时间】:2020-02-13 22:19:12
【问题描述】:

我想让用户只输入整数或浮点数。现在我只能输入整数,它允许输入点或逗号。找不到合适的正则表达式来验证整数和浮点数。

<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);
      }
    }
  }

【问题讨论】:

  • 您拥有的正则表达式很好,应该可以工作,您能否更具体地说明您遇到问题的地方,并且您应该使用type='number'

标签: javascript html regex reactjs


【解决方案1】:

你可以使用

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>

【讨论】:

    【解决方案2】:

    您的正则表达式应该匹配点,但它似乎不匹配逗号。您可以尝试以下方法:

    ^[0-9]+([,.][0-9]+)?$

    供参考:

    [0-9] 匹配数字 0-9。

    + 匹配一次到无限次,尽可能多次。

    [,.] 匹配逗号或点。

    可能有一种方法可以简化这个正则表达式,但我认为它应该可以工作。

    你可以在这里测试它:https://regex101.com/r/V0J63U/1

    --更新--

    为了也匹配前导符号(即 +/-),您可以将 ^[+-]? 添加到模式的开头:

    ^[+-]?[0-9]+([,.][0-9]+)?$

    你可以在这里测试:https://regex101.com/r/cQylX3/1

    感谢@CodeManiac 的提示!

    【讨论】:

    • 现在它不会匹配前导符号,您需要在模式开头添加^[+-]?
    • @CodeManiac 也添加了该内容并更新了链接。泰。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2020-02-18
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多