正则表达式允许在HTML输入框中仅输入字母和空格。

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


你想允许多少个空格? - Gaurav Rana
3个回答

4

将您的正则表达式更改为/[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>


1

更改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>


0

我没有使用过它,但是像下面这样的东西应该可以解决你的问题-

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

或者

如果是针对 onkeydown 事件的话,应该是:

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

捕获实际键盘按键。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接