【问题标题】:How can I make my input to be only limited to a maximum of 10 numbers and don't allow any characters?如何使我的输入仅限于最多 10 个数字并且不允许任何字符?
【发布时间】:2022-01-13 16:34:48
【问题描述】:

我希望能够为输入的电话号码设置最大长度,并且也不允许任何字符。但是,对于下面的格式,它确实限制该人输入 10 个字符,但它也允许添加任何其他字符。

现在,如果我将 type 更改为 type="number" maxLength 将不起作用,并且 [minus(-) 或 plus(+)] 等字符仍将通过。

如何使我的输入仅限于最多 10 个数字并且不允许任何字符?

<input
  placeholder="Telephone Number"
  className="input_fields telephone_no"
  type="tel"
  maxLength={"10"}
  name="phoneNumber"
  id="teacher_telephone_no"
  value={this.state.user.phoneNumber}
  onChange={e =>
    this.setState({
      user: {
        ...this.state.user,
        [e.target.name]: e.target.value
      }
    })
  }
/>

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    您可以在设置状态之前使用regex 测试您的输入,如:

         <input
            placeholder="Telephone Number"
            className="input_fields telephone_no"
            type="tel"
            maxLength={"10"}
            name="phoneNumber"
            id="teacher_telephone_no"
            value={user}
            onChange={(e) => {
              if (/^[0-9]{1,10}$/.test(e.target.value)) {
                 this.setState({
                   user: {
                   ...this.state.user,
                   [e.target.name]: e.target.value
                   }
                })
              }
            }}
          />
    

    【讨论】:

    • 非常感谢你的工作:)
    【解决方案2】:

    您可以使用正则表达式和keyup 事件来防止符号输入。

    let input = document.querySelector('input')
    input.onkeyup = function() {
      input.value = input.value.replace(/[^\d]/, "")
    
    }
    &lt;input placeholder="Telephone Number" className="input_fields telephone_no" type="tel" maxLength={ "10"} name="phoneNumber" id="teacher_telephone_no" /&gt;

    【讨论】:

    • 不幸的是模式属性不起作用
    • @marksmith,我可以建议您使用正则表达式,您觉得可以吗?
    • 好的,你有什么建议?
    • @marksmith,更新代码,检查是否有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多