Freelance of Dev biznet
12/24/2019 - 1:07 PM

Password strength and compare

Ajoute une jauge de force du mot de passe et compare les deux champs.

<div id="passStrength">
	<p><input type="password" id="passNew" placeholder="Nouveau mot de passe" /></p>
	<div id="passProgress">
		<span class="low"></span>
		<span class="medium"></span>
		<span class="high"></span>
		<span class="extra"></span>
	</div>
	<p><input type="password" id="passConfirm" placeholder="Confirmation du nouveau mot de passe" /></p>
	<span id="passTxt"></span>
</div>
#passProgress {
	display: flex;
	justify-content: space-around;
}

#passTxt {
	text-align: center;
	display: block;
}

#passProgress span {
	width: 22%;
	height: 8px;
	display: block;
	background-color: rgb(180,180,180);
	border-radius: 4px;
}

#passProgress span.low.active { background-color: #ec4c46; }
#passProgress span.medium.active { background-color: #ffa200; }
#passProgress span.high.active { background-color: #91ca31; }
#passProgress span.extra.active { background-color: #21dc12; }
var passConfirmError = true;
var passStrengthError = true;
// Ces deux variables passent en "true" si tout est ok.

$('#passNew').on('input', function() {
	var passNew = $('#passNew').val();
	var passScore = 0;

	passStrengthError = true;

	if(passNew.length < 6) {
		$('#passProgress span.low').addClass('active');
		$('#passProgress span.medium, #passProgress span.high, #passProgress span.extra').removeClass('active');
	} else {
		$('#passProgress span.low, #passProgress span.medium').addClass('active');
		$('#passProgress span.high, #passProgress span.extra').removeClass('active');

		if(passNew.match(/\d+/)) { passScore++; }
		if(passNew.match(/[a-z]/)) { passScore++; }
		if(passNew.match(/[A-Z]/)) { passScore++; }
		if(passNew.match(/[!@#$%^&*(),.?":{}|<>]/)) { passScore++; }

		if(passScore > 1) {
			$('#passProgress span.high').addClass('active');
			passStrengthError = false;
		}

		if(passScore > 2) {
			$('#passProgress span.extra').addClass('active');
			passStrengthError = false;
		}
	}
});

$('#passConfirm').on('input', function() {
	var passNew = $('#passNew').val();
	var passConfirm = $('#passConfirm').val();

	passConfirmError = true;

	if(passNew != passConfirm) {
		$('#passTxt').text('Les mots de passe ne correspondent pas');
	} else {
		passConfirmError = false;
		$('#passTxt').text('');
	}
});