如何使用正则表达式进行正确的输入验证? [英] How to make proper Input validation with regex?

查看:22
本文介绍了如何使用正则表达式进行正确的输入验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want let users enter only integer or floating numbers. Right now I can only enter integer numbers,it does allow type dot or comma . Cant find proper regex to validate both integer and floating numbers.

<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*)?$/;

用于实时验证.对于最终验证,使用

for live validation. For the final validation, use

const rx_final = /^[+-]?\d+(?:[.,]\d+)?$/;

或者,更好的是,只需在 pattern 属性中使用正则表达式:pattern="[+-]?\d*(?:[.,]\d*)?".

Or, better, just use the regex in the pattern attribute: pattern="[+-]?\d*(?:[.,]\d*)?".

注意

  • ^ - 字符串的开始
  • [+-]? - 一个可选的 +-
  • \d* - 0 个或多个数字
  • (?:[.,]\d*)? - ., 的可选序列,然后是 0 个或多个数字
  • $ - 字符串结束.
  • ^ - start of string
  • [+-]? - an optional + or -
  • \d* - 0 or more digits
  • (?:[.,]\d*)? - an optional sequence of . or , and then 0 or more digits
  • $ - end of string.

在最终验证中,使用 \d+ 代替 \d* 来匹配一个或多个数字而不是零或更多位数.

In final validation, \d+ is used instead of \d* to match one or more digits as opposed tozero or more 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>

这篇关于如何使用正则表达式进行正确的输入验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆