This regex may also suit you:
/^[a-z][a-z\d]?$/i
The flag i
will dispense with the use of the method .toUpperCase()
, because it will ignore if the letter is uppercase or lowercase.
Explanation:
[a-z] O primeiro caractere é obrigatório ser uma letra
[a-z\d] O segundo caractere é opcional, mas se existir
deverá ser uma letra [a-z] ou um número \d
The ?
causes the [a-z\d]
is optional. The ^
and the $
define the string a maximum of 2 characters from the first.
Then the if
would be:
if(/^[a-z][a-z\d]?$/i.test(value)){
callback(true);
}else{
callback(false);
}
Testing:
function valida(i){
if(/^[a-z][a-z\d]?$/i.test(i)){
callback(true, i);
}else{
callback(false, i);
}
}
function callback(x, i){
console.clear();
console.log("'"+ i +"' é "+ x);
}
<p>Clique nos botões</p>
<button onclick="valida('a')">a</button>
<button onclick="valida('A')">A</button>
<button onclick="valida('aB')">aB</button>
<button onclick="valida('a#')">a#</button>
<button onclick="valida('a1')">a1</button>
<button onclick="valida('3A')">3A</button>
Ana, you said clearly that the first character is always a letter, ok. And in the second character, can come any character, example:
!#$@%&*_-
?– Sam
@sam the options for the second house will only be: see nothing, a letter or number.
– Ana Caroline Rodrigues