I am validating an input for a password, where I require that the user must enter at least one special character, for example: (@#$%&.), in my code with jquery I am detecting the keyup event to evaluate what the user writes, while I write in the input all the characters are written correctly, until I try to do the @ with the key combination Alt + 64, the event detects when the Alt is pressed but in the result of the jquery code where I look for the value of the input it is not there the @ even though it is in the input.
This is my jquery code to evaluate the keyup event:
function validate_pass(element) {
let password = $(element).val();
if (!(/^(.{8,20}$)/.test(password))) {
return 'It must be between 8 and 20 characters.';
}
else if (!(/^(?=.*[A-Z])/.test(password))) {
return 'It must contain at least one capital letter.';
}
else if (!(/^(?=.*[a-z])/.test(password))) {
return 'It must contain at least one lowercase letter.';
}
else if (!(/^(?=.*[0-9])/.test(password))) {
return 'It must contain at least one digit (0-9).';
}
else if (!(/^(?=.*[@#$%&])/.test(password))) {
return "Must contain special characters (@#$%&).";
}
return true;
}
$('#user-pass').on('keyup',(e)=>{
if(e.which == 20 || e.which == 16){ //prevent bloq mayus and shift
return false;
}
console.log($('#user-pass').val());
let resp = validate_pass('#user-pass');
if(resp == true){
$('label[for="user-pass"]').text('Password').css('color','#9e9e9e');
$('#user-pass').removeClass('invalid');
$('#user-pass').addClass('valid');
}else{
$('label[for="user-pass"]').text(resp).css('color','red');
$('#user-pass').addClass('invalid');
}
});
Let’s imagine that I write the following password in the input so that I test the code: Jhon000@
In the console I get the following results:
J
Jh
Jho
John
Jhon0
Jhon00
Jhon000
but when I execute the combination of Alt + 64 to write the @ the console shows me this again in the log:
Jhon000
and I have to press some other key so that the keyup event shows me Jhon000@ in the console, for example I use the same Alt key.
2
Answers
I found a strange solution, but it works. I just had to put a setTimeout inside the code that detects the event, like this:
and this just fixed the problem.
I found this solution in the following link: https://github.com/jquery/api.jquery.com/issues/386
The problem is that the
keyup
event is triggered every time a key is being released.Here’s an example that shows the actual behavior:
When you use Alt+Num codes, the
keyup
event is being triggered every time you release a number. The keyboard however does not input anything into the field as it waits for you to release the Alt key.Once you release the Alt key, it actually does trigger the
keyup
event. However, it takes a fraction of a second for your computer to get the correct special character, by which time thekeyup
event is already finished. Hence setting a timeout "fixes" the issue, as it simply gives your pc the time it needs to input the special character.