Script for checking password strength

I have a jQuery script that checks for the strength of a password. The code looks like this (with more more of those "blocks"):

if(passwordLC && lessThan12Password)
{
$('.passwordStrenght').animate({width:'75px',height:'5px'},200).show();$('.passwordStrenght').css('background-color',red);
$('#password').css('border-color',green);$('.passwordStrenghtInfo').text(weak).show();
passwordErrors = true;
}else

if(passwordUC && lessThan12Password)
{
$('.passwordStrenght').animate({width:'75px',height:'5px'},200).show();$('.passwordStrenght').css('background-color',red);
$('#password').css('border-color',green);$('.passwordStrenghtInfo').text(weak).show();
passwordErrors = true;
}else

if(passwordN && lessThan12Password)
{
$('.passwordStrenght').animate({width:'75px',height:'5px'},200).show();$('.passwordStrenght').css('background-color',red);
$('#password').css('border-color',green);$('.passwordStrenghtInfo').text(weak).show();
passwordErrors = true;
}else


And it goes on and on...

Is there a way to reduce all that code to something simpler and efficient, or am I stuck with those horrible "blocks" of repeated code?

1 Answer

The solution depends on your exact requirements and the context. In your case, you could simplify the if-condition like below. If all fit into one if, you can write your code block there only once. If you need it and can't unify your condition, make it a function.

Here, I'm using a combined approach. I put the code from your if into a function, jQuery objects are cached and don't have to be recreated (but are still protected from outside modification because they only exist inside the scope of that function). And I combined all the conditions I could see in your example.

var indicateBadPassword = (function() {
var $passwordStrength =$('.passwordStrength'),
$password =$('#password'),
$passwordStrengthInfo =$('.passwordStrenghtInfo');
return function() {
$passwordStrength. animate({width:'75px',height:'5px'},200). show(). css('background-color',red);$password.css('border-color',green);
\$passwordStrengthInfo.text(weak).show();
passwordErrors = true;

}
})();
if (lessThan12Password && (passwordLC || passwordUC || passwordN)) {
indicateBadPassword();
}