Arkhall Arkhall - 3 months ago 7
jQuery Question

JQuery - Password regex when empty

I'm working on a regex for password and I touch the goal :)

When the user tips a password, an error message displays and when he fills the conditions, the error message disapears.

The only problem, is the situation when the user uses the backspace touch in order to clean the password field, the error message still displays :

Here is the function

$('#id_password.form-control').on('input', function(){
$('span.error-keyup-password').remove();
var inputVal = $(this).val();
var passwordReg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{8,}$/;
if(!passwordReg.test(inputVal)) {
$(this).after('<span style="color:red;" class="error error-keyup-password">Au moins un chiffre, un lettre, un caractère spécial et 8 caractères.</span>');
} else if (document.querySelector('id_password').value == ""){
$('span.error-keyup-password').remove();
}
});


I'm sure the problem is on my regex, or in the second condition, but I'm stuck for the moment. If you have some ideas, I'm open =)

Edit : If that can help you, I can give you another function with the email address and it works perfectly =)

$('#id_email.form-control').on('input', function(){
$('span.error-keyup-email').remove();
var inputVal = $(this).val();
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(inputVal)){
$(this).after('<span style="color:red;" class="error error-keyup-email">Format invalide.</span>');
}
});


Thank you for the help you can give and have a nice day =)

Answer

This should work:

   $('#id_password.form-control').on('input', function(){
    $('span.error-keyup-password').remove();
    var inputVal = $(this).val();
    var passwordReg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{8,}$/;
    if(!passwordReg.test(inputVal)) {
        $(this).after('<span style="color:red;" class="error error-keyup-password">Au moins un chiffre, un lettre, un caractère spécial et 8 caractères.</span>');
    }  
   if ($(this).val()  == ""){
        $('span.error-keyup-password').remove();
    }
});
Comments