首页 > 解决方案 > 正则表达式仅在 html 输入框中允许字母和空格

问题描述

我想在输入框中只允许字母和空格,如“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>

标签: htmlregex

解决方案


改变你的正则表达式/[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>


推荐阅读