【问题标题】:Regex allow letters and space only in html input box正则表达式仅在 html 输入框中允许字母和空格
【发布时间】:2018-12-27 11:39:20
【问题描述】:

我只想在“john deo”之类的输入框中允许输入字母和空格。但以上不适用于下面的正则表达式,并且不允许空间。

<!DOCTYPE html">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
</head>

<body>
<label>full name
<input type="text" name="textfield" onkeydown="return /[a-z]/i.test(event.key)"
    onblur="if (this.value == '') {this.value = '';}"
    onfocus="if (this.value == '') {this.value = '';}"/>
</label>
</body>
</html>

【问题讨论】:

  • 您要允许多少个空格?

标签: html regex


【解决方案1】:

更改您的正则表达式,例如 /[a-z, ]/i

<!DOCTYPE html">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
</head>

<body>
<label>full name
<input type="text" name="textfield" onkeydown="return /[a-z, ]/i.test(event.key)"
    onblur="if (this.value == '') {this.value = '';}"
    onfocus="if (this.value == '') {this.value = '';}"/>
</label>
</body>
</html>

【讨论】:

    【解决方案2】:

    更改oninput="this.value = this.value.replace(/[^a-z, ]/, '')"

    <!DOCTYPE html">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Untitled Document</title>
    </head>
    
    <body>
    <label>full name
    <input type="text" name="textfield" oninput="this.value = this.value.replace(/[^a-z, ]/, '')" />
    </label>
    </body>
    </html>

    【讨论】:

      【解决方案3】:

      没用过,但是下面的东西应该可以解决你的问题-

      onkeydown = "return((event.keyCode >= 65 && event.keyCode <= 120) || (event.keyCode==32));"
      

      或者

      如果是onkeydown事件,那么应该是:

      return (event.keyCode>=65 && event.keyCode<=90 || event.keyCode==32);
      

      捕获实际的键盘键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-14
        • 2016-01-03
        • 2020-01-08
        • 2016-08-22
        • 2016-02-21
        • 2017-06-17
        • 1970-01-01
        相关资源
        最近更新 更多