J'ai écrit un code de validation pour un mot de passe et confirmer le mot de passe qui vérifie s'ils correspondent ou non. De plus, il existe une condition qui vérifie si la longueur de mon mot de passe est inférieure à 6 caractères et écrit/affiche une erreur s’ils sont inférieurs à 6 caractères. Mais mon code ne fonctionne pas correctement: lorsque je passe au champ 2, la condition du champ 1 n'est pas vérifiée et si les deux conditions sont correctes, l'erreur persiste.
Voici mon code:
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
if(pass1.length > 5){
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
Utilisez le code ci-dessous. Tout d'abord , pass1.length
n'est pas correct. Vous devriez écrire pass1.value.length
. Deuxièmement , j'ai ajouté en comparant les 2 blocs à la fin, car vous devriez d'abord vérifier la longueur du premier bloc. En outre, la fonction doit également être appelée lors des modifications du premier bloc.
Bonne chance!
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value.length > 5)
{
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
else
{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
return;
}
if(pass1.value == pass2.value)
{
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else
{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass(); return false;" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
Essaye ça:
if(pass1.value.length > 5)
avant:
if(pass1.length > 5)
après:
if(pass1.value.length > 5)
et vous devriez vérifier l'égalité après tout, comme la longueur ou les caractères autorisés, etc.
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value.length > 5 && pass2.value.length > 5)
{
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
if(pass1.value == pass2.value)
{
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else
{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
else
{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
if (pass1.value.length > 5)
Assurez-vous de ne pas appliquer trim (), car trim supprimera les espaces et le vide dans le mot de passe n'est pas un caractère valide.
Lorsque vous vérifiez la longueur de pass1, vous ne vérifiez pas réellement sa valeur - pass1.length > 5
- vous devez la changer en pass1.value.length > 5
Tu peux faire:
if (pass1.value.trim().length > 5)
Pour vérifier la longueur, vous devriez écrire comme ceci
if (pass1.value.length > 5)
et puis votre code fonctionne bien
Vous pouvez tirer parti de l’expression régulière pour effectuer la validation pour vous ..__Par exemple: j’autorise certains caractères spéciaux dans ce mot de passe et le nombre est supérieur à 6.
regex = pass1.value.search(/^[a-zA-Z0-9+&@#/%?=~_|!:,.;]{6,}+$/);
if(regex){
message.innerHTML="Invalid Password.";
}else{
message.innerHTML = " you have to enter at least 6 digit!";
}
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
if(pass1.value.length > 5){
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
La tâche apparemment simple de validation du mot de passe peut devenir complexe et il peut être difficile de déterminer pourquoi le code ne fonctionne pas comme prévu. Une partie importante du défi consiste à spécifier la logique conditionnelle, puis à convertir cette logique en code opérationnel.
Vous voulez atteindre les objectifs suivants:
Une façon de convertir cela en logique conditionnelle (en pseudocode) est la suivante:
if (password length is less than 6)
inform user that password should be at least 6 characters
else if (passwords do not match)
ask user to confirm password
else
inform user that passwords match, all is ok
Mais mon code ne fonctionne pas correctement: lorsque je passe au champ 2, la condition du champ 1 n'est pas vérifiée et si les deux conditions sont correctes, l'erreur persiste.
Votre code suit une logique différente (en pseudocode):
if (passwords match)
inform user that passwords match, all is ok
else
inform user that passwords do not match
if (password is more than 5 characters)
inform user that the password is long enough
else
inform user that the password should be at least 6 characters
Un problème dans votre code est que la longueur du mot de passe est la dernière chose à vérifier. Par conséquent, la première vérification si/else est redondante (elle ne produira jamais de retour pertinent, même lorsque les mots de passe sont identiques), car votre code finira toujours par fournir commentaires sur la longueur du mot de passe.
Un autre problème est que votre code accepterait des mots de passe qui correspondent même s'ils ont moins de 6 caractères. C'est pourquoi vous souhaitez d'abord vérifier la longueur du mot de passe, puis vérifier si les deux mots de passe correspondent.
De plus, votre code n'exécute ces contrôles que lorsque l'utilisateur écrit dans le champ 2 ('# pass2'), vous devez également ajouter un gestionnaire d'événements à 'onkeyup' du champ 1.
Ainsi, votre logique de code doit être réécrite. Voici l'une des façons de procéder:
function checkPass() {
var neutralColor = '#fff'; // 'white';
var badColor = '#f66'; // 'red';
var goodColor = '#6f6'; // 'green';
var password1 = getElm('pass1').value;
var password2 = getElm('pass2').value;
//if password length is less than 6
if (password1.length < 6) {
feedback('Enter a password of at least 6 characters');
//we do not care about pass2 when pass1 is too short
setBGColor('pass2', neutralColor);
//if pass1 is blank, set neutral background
if (password1.length === 0) {
setBGColor('pass1', neutralColor);
} else {
setBGColor('pass1', badColor);
}
//else if passwords do not match
} else if (password2 !== password1) {
//we now know that pass1 is long enough
feedback('Confirm password');
setBGColor('pass1', goodColor);
//if pass2 is blank, set neutral background
if (password2.length === 0) {
setBGColor('pass2', neutralColor);
} else {
setBGColor('pass2', badColor);
}
//else all is well
} else {
feedback('Passwords match');
setBGColor('pass1', goodColor);
setBGColor('pass2', goodColor);
}
}
//helper function for document.getElementById()
function getElm(id) {
return document.getElementById(id);
}
//helper function for setting background color
function setBGColor(id, value) {
getElm(id).style.backgroundColor = value;
}
//helper function for feedback message
function feedback(msg) {
getElm('error-nwl').innerHTML = msg;
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass()"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass()" />
<div id="error-nwl">Enter a password of at least 6 characters</div>
Recherchez le commentaire ajouté pour les modifications apportées, car cela fonctionne maintenant.
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
if(pass1.value.length > 5){ ////////just added value here//
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
function checkPassSize(field) {
var pass = document.getElementById(field);
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass.value && pass.value.length > 5) {
pass.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
return true;
} else {
pass.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
return false;
}
}
function checkPass() {
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(checkPassSize('pass1') && checkPassSize('pass2')){
if (pass1.value == pass2.value) {
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
} else {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
}
<input name="password" type="password" placeholder="password"
id="pass1" onkeyup="checkPassSize('pass1');" />
<input name="repeatpassword" type="password"
placeholder="confirm password" id="pass2"
onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
Il semble que vous souhaitiez faire certaines choses.
Mes suggestions,
Le code suivant devrait faire ce que vous recherchez.
function checkPass() {
var getTag = Id => document.getElementById(Id);
var pass1 = getTag('pass1');
var pass2 = getTag('pass2');
var message = getTag('error-nwl');
var str;
//Logic that handles Password.
if (!pass1.value)
pass1.removeAttribute('valid');
else if (pass1.value.length < 6) {
pass1.setAttribute('valid', false)
str = " you have to enter at least 6 digit!";
} else {
if (!pass2.value)
str=" character number ok!";
pass1.setAttribute('valid', true);}
//Logic that handles Retype.
if (!pass2.value)
pass2.removeAttribute('valid');
else if (pass1.value != pass2.value) {
pass2.setAttribute('valid', false);
str = " These passwords don't match";
} else
pass2.setAttribute('valid', true);
//Logic that handles the display of message.
message.removeAttribute('valid');
if (pass1.value && pass2.value && !str) {
message.setAttribute('valid', true);
message.innerHTML = "ok!"
} else if (str) {
message.innerHTML = str;
} else
message.innerHTML = '';
return !!message.valid;
}
#pass1[valid=true] {
background: #66cc66
}
#pass1[valid=false] {
background: #ff6666
}
#pass2[valid=true] {
background: #66cc66
}
#pass2[valid=false] {
background: #ff6666
}
#error-nwl {
color: #ff6666
}
#error-nwl[valid=true] {
color: #66cc66
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass()" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass()" />
<div id="error-nwl"></div>
Si vous utilisez jQuery, vous pouvez utiliser ce plugin jQuery Validation
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required to be the same as #other</title>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">
</head>
<body>
<form id="myform">
<label for="password">Password</label>
<input id="password" name="password" />
<br/>
<input type="submit" value="Validate!">
</form>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
password: {
minlength: 6,
maxlength: 25,
required: true
}
}
});
</script>
</body>
</html>
Utiliser le code ci-dessous
valid=pass1.value.search(/^[A-Za-z0-9@_]{6,20}$/);
if(valid != 0){
message.innerHTML="Invalid Password.";
}else if(pass1.value.length < 6){
message.innerHTML = " you have to enter at least 6 digit!"
}
Votre problème est de vérifier la longueur d'un seul nœud DOM, au lieu de la longueur de la valeur des nœuds DOM.
Ce que vous avez actuellement équivaut à
var pass1 = document.getElementById('pass1');
if ( pass1.length > 5 ) {...
Un seul nœud DOM a uniquement une longueur de 1
; s'il est trouvé, il ne pourra jamais être plus de 5
.
Ce que tu voulais, c'était vérifier la longueur de la valeur
var pass1 = document.getElementById('pass1');
if ( pass1.value.length > 5 ) {...
Mais vous voulez vraiment faire cela en tapant dans le premier champ de mot de passe, pas dans le second.
En utilisant des gestionnaires d'événements appropriés, de meilleurs contrôles et des classes pour les messages, ce serait le moyen de le faire.
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
function msg(_msg, good, time) {
message.innerHTML = _msg;
message.classList.toggle('bad', !good);
message.classList.add('visible');
setTimeout(function() {message.classList.remove('visible')}, time);
}
pass1.addEventListener('input', function() {
this.classList.remove('bad');
this.classList.remove('good');
if (this.value.length > 5) {
this.classList.add('good');
msg("Character number ok!", true, 1800);
}
});
pass1.addEventListener('blur', function() {
if (this.value.length <= 5) {
this.classList.remove('good');
this.classList.add('bad');
msg("You have to enter at least 6 digit!", false, 1800);
} else if (pass1.value !== pass2.value) {
pass2.classList.remove('good');
pass2.classList.add('bad');
msg("Passwords don't match", false, 3000);
}
});
pass2.addEventListener('input', function() {
if (this.value.length > 5) {
var matches = pass1.value === pass2.value;
var _message = matches ? "Passwords match!" : "Passwords don't match";
pass2.classList.toggle('good', matches);
pass2.classList.toggle('bad', !matches);
msg(_message, matches, 3000);
} else {
message.classList.remove('visible');
this.classList.remove('good');
this.classList.remove('bad');
}
});
pass2.addEventListener('blur', function() {
var matches = pass1.value === pass2.value;
if (!matches) {
pass2.classList.remove('good');
pass2.classList.add('bad');
msg("Passwords don't match", matches, 3000);
}
});
#pass1.bad,
#pass2.bad {
background: #ff6666;
}
#pass1.good,
#pass2.good {
background: #66cc66;
}
#error-nwl {
opacity: 0;
color: #66cc66;
transition: opacity 0.3s ease-in-out;
}
#error-nwl.bad {
color: #ff6666;
}
#error-nwl.visible {
opacity: 1;
}
<input name="password" type="password" placeholder="password" id="pass1" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" />
<div id="error-nwl"></div>
Voici le code de travail .. Changez pass1.length
en pass1.value.length
et mettez à jour les couleurs des deux champs de texte en fonction des validations.
<html>
<head>
<script>
function checkPass() {
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass1.value == pass2.value) {
pass2.style.backgroundColor = goodColor;
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
} else {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
if (pass1.value.length > 5 && pass1.value == pass2.value) {
pass1.style.backgroundColor = goodColor;
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
} else {
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
</script>
</head>
<body>
<input name="password" type="password" placeholder="password" onkeyup="checkPass();" id="pass1" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
</body>
</html>
Ce code valide les deux champs lors de la frappe.
<!DOCTYPE html>
<html>
<body>
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="setStyle(this,document.getElementById('pass2'));" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="setStyle(this,document.getElementById('pass1'));" />
<div id="error-nwl"></div>
<script>
function isValidLength(element) {
return (element.value.length > 5);
}
function isEqual(element1, element2) {
if (element1.value.length > 0 && element2.value.length > 0)
return (element1.value == element2.value);
return true;
}
function setStyle(element, element2) {
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
var isValidPWD = isValidLength(element) && isEqual(element, element2);
if (isValidPWD) {
if (isValidLength(element)) {
element.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
if (isEqual(element, element2)) {
element.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
} else {
if (!isValidLength(element)) {
element.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
if (!isEqual(element, element2)) {
element.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
}
</script>
</body>
</html>
Il est préférable d'affecter le programme d'écoute d'événement aux éléments du code après le chargement du DOM afin de pouvoir omettre plusieurs appels à getElementById. Néanmoins, votre code est corrigé:
var goodColor = "#66cc66", badColor = "#ff6666";
function checkPass() {
message = document.getElementById('error-nwl');
pass1 = document.getElementById('pass1');
pass2 = document.getElementById('pass2');
if (pass1.value.length > 5) {
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
if (pass2.value == pass1.value) {
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
else {
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass()" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass()" />
<div id="error-nwl"></div>
vous pouvez utiliser deux fonctions pour faire ce travail.
checkPass1 () vérifie que le mot de passe est suffisamment long. checkPass2 () vérifie que ces mots de passe correspondent. Dans le cas où un utilisateur peut d'abord remplir le # pass2, j'ajoute checkPass2 () dans checkPass1 ().
function checkPass1()
{
var pass1 = document.getElementById('pass1');
var message = document.getElementById('length-error');
var goodColor = "#66cc66";
var badColor = "#ff6666";
var normalColor = "#ffffff"
if (pass1.value.length <= 5)
{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
else
{
pass1.style.backgroundColor = normalColor;
message.style.color = goodColor;
message.innerHTML = " the length of password is long enough";
}
checkPass2();
}
function checkPass2()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('confirm-error');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value)
{
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else
{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass1()"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass2()" />
<div id="length-error"></div>
<div id="confirm-error"></div>
vous pouvez utiliser validform.js.
Par exemple:
<script type="text/javascript" src="http://validform.rjboy.cn/wp-content/themes/validform/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="http://validform.rjboy.cn/Validform/v5.1/Validform_v5.1_min.js"></script>
<script>
$(".demoform").Validform();
</script>
<form class="demoform">
<input type="password" value="" name="userpassword" datatype="*6-15" errormsg="Password range between 6~15 bits!" />
<input type="password" value="" name="userpassword2" datatype="*" recheck="userpassword" errormsg="The account passwords you entered for the two time were not consistent." /></form>
Vous devez garder à l'esprit qu'il existe de nombreuses possibilités d'événement et l'ordre des événements.
if(user>0 and user<5){//output username should be 6}
if(pass>0 and pass<5){//output password should be 6}
if(user>5 and pass>5){
if(user==pass){//password match}
else{//invalid password}
}
J'ai modifié le code pour pouvoir contourner
function checkPass() {
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass1.value.length > 5) {
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
if (pass1.value == pass2.value) {
pass1.style.backgroundColor = goodColor;
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!";
} else {
if (pass2.value.length > 0) {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match";
}
}
} else {
if (pass1.value.length <= 5 && pass1.value.length > 0) {
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit user!";
if (pass2.value.length > 0) {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
}
}
if (pass2.value.length <= 5 && pass2.value.length > 0) {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit pass!"
}
}
}
<html>
<body>
<input name="password" type="password" placeholder="password" onkeyup="checkPass();" id="pass1" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass();" />
<div id="error-nwl"></div>
</body>
</html>
Cela peut également être fait en appelant la méthode onkeyup dans les deux champs et en écrivant des fonctions différentes pour valider les champs, cela garantira une plus grande flexibilité et permettra de contourner la plupart des cas. Vous pouvez également être intéressé par l'ajout d'autres événements tels que onBlur à tester lorsque l'utilisateur prend le focus est déplacé.
J'espère que cela répond à votre question
Essayez ceci!
function resetcol()
{
pass1.style = "";
pass2.style = "";
}
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass1.value == pass2.value && pass1.value.length > 5){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else{
pass1.style =
message.style.color = badColor;
message.innerHTML = "Bad input. your passwords must match, and be at least 6 characters long."
}
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="resetcol();"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="resetcol();" onchange="checkPass(); return false;" />
<div id="error-nwl"></div>
Vous pouvez déplacer le deuxième bloc if else
dans la première if
et obtenir ce que vous auriez pu souhaiter. Vous devez également modifier pass1.length
en pass1.value.length
.
Je pense aussi que vous devriez vérifier les changements sur les deux zones de saisie. Si vous ne le faites pas, l'utilisateur peut revenir à la première zone de saisie et modifier le mot de passe par la suite.
Voici le code mis à jour.
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value.length > 5){
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
//message.innerHTML = "character number ok!"
if(pass1.value == pass2.value) {
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Ok!"
}
else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "These passwords don't match!"
}
}
else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "You have to enter at least 6 digits!"
}
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass(); return false;"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>