I'm using a regular expression to prevent characters other than letters from being written to a textarea:
/[A-Za-Z]/ig
but it throws me this error related to the regular expression:
Range out of order in character class
Why does this happen?
window.addEventListener("DOMContentLoaded", checker);
function checker() {
var textArea = document.getElementsByTagName("textarea");
for (let element of textArea) {
element.addEventListener("keypress", event => {
var letra = "which" in event ? event.which : event.keyCode,
patron = /[A-Za-Z]/ig;
if (!patron.test(letra)) {
event.preventDefault();
return false;
}
});
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<textarea cols="40" rows="10"></textarea></textarea>
</body>
</html>
The error " Range out of order in character class " means that, within the character class , there is a range upside down. In a character class you can use any range, for example
[!-z]
,[#-@]
or whatever you want, as long as the first has a character value less than the second.-We usually talk about ASCII code because the basic Latin block is the one we use the most, but it also goes for any code point value in Unicode, not just the most common ones between 0 and 127.
There are 3 reasons why the error can be generated:
-
, but it was not escaped.Example: when you want to match one of these symbols
[,-!"#]
, the hyphen has to be escaped so as not to generate a range, like[,\-!"#]
(or be at the beginning or end of the class, where it is never a range).Example: to match the text
"[ax - b]"
, the leading bracket must be escaped so that it does not generate a class, such as\[ax - b]
.[a-Z]
.In your case,
a-Z
it's wrong, because laa
has the value 97 and la hasZ
the value 90 (it's backwards). Instead, it could be[Z-a]
, which includes the charactersZ
,[
,\
,]
,^
,_
,`
anda
.- I know, it was probably just a typo but I wanted to explain it.
The regex that matches a letter from a to z in uppercase or lowercase is
/^[A-Za-z]$/
.Or, what is the same (if we use the switch
/i
to ignore case):/^[a-z]$/i
But let's not forget the ñ and the accented vowels in Spanish:
The regex error is because you included the in the characters AZ and aZ and there is no character range aZ but az .
Also as I see the code, you must use event.key
Modified code: