Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  145] [ 1]  / answers: 1 / hits: 18617  / 11 Years ago, wed, march 6, 2013, 12:00:00

Here is a fiddle to start - http://jsfiddle.net/zuVpx/1/



Javascript code:



<script>
function validate(e) {
var regex = new RegExp([a-zA-Z0-9]);
var key = e.keyCode || e.which;
key = String.fromCharCode(key);

if(!regex.test(key)) {
e.returnValue = false;
if(e.preventDefault) {
e.preventDefault();
}
}
}
</script>


HTML code:



<input type=text onkeypress=validate(event) />


I want only characters and numbers. Keys like backspace, delete, capslock and arrowkeys etc should work.



Thanks in advance.


More From » jquery

 Answers
10

[old answer, update] KeyboardEvent.charCode and KeyboardEvent.keyCode are deprecated. We should use KeyboardEvent.key.




document.querySelector(`#validate`).onkeypress = e => /[a-z0-9]/i.test(e.key);

<input type=text id=validate>




Add an id to the input (e.g. 'validate') and use:


document.querySelector('#validate').onkeypress = validate;

function validate(e) {
e = e || event;
return /[a-z0-9]/i.test(
String.fromCharCode(e.charCode || e.keyCode)
) || !e.charCode && e.keyCode < 48;
}

[#79800] Tuesday, March 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;