Regex allow letters and space only in html input box

Viewed 2743

I want to allow only letters and space in input box like "john deo". but the above doesn't work with below Regex and it is not allowing space.

<!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>

3 Answers

change your regular expression like /[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>

Change 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>

Haven't used it but something like following should resolve your problem-

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

Or

If it is for onkeydown event, then it should be:

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

to capture the actual keyboard key.

Related