web-dev-qa-db-fra.com

Messages d'erreur individuels pour les champs de formulaire vides à l'aide de JavaScript

Je dois valider mon formulaire à l'aide de JavaScript, car iPhone/Safari ne reconnaît pas l'attribut required. Je souhaite que des messages d'erreur individuels apparaissent sous chaque champ input vide.

Mon code fonctionne, mais le message d'erreur individuel ne disparaît pas lorsque le champ est rempli. De plus, j'aimerais que tous les messages apparaissent initialement, pour tous les champs vides (pas un par un). Je suis très nouveau pour JavaScript, désolé.

Mon HTML:

<form onsubmit="return validateForm()" method="post" action="form.php" name="english_registration_form" id="english_registration_form">
        <input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
        <span class="error"><p id="name_error"></p></span>
        <input type="email" id="email" name="email" required placeholder="Email">
        <span class="error"><p id="email_error"></p></span>
        <input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
        <span class="error"><p id="telephone_error"></p></span>
        <button class="register_button" type="submit" value="submit">Register Now</button>
    </form>

Et mon JavaScript:

<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;

if (x == null || x == "") {
    nameError = "Please enter your name";
    document.getElementById("name_error").innerHTML = nameError; 
    return false;
} 

else if (y == null || y == "") {
    emailError = "Please enter your email";
    document.getElementById("email_error").innerHTML = emailError;
    return false;
} 

else if (z == null || z == "") {        
    telephoneError = "Please enter your telephone";
    document.getElementById("telephone_error").innerHTML = telephoneError;
    return false;
} 

else {return true;}
}
</script>

Merci de votre aide.

4
Sophie

Voici une solution qui affiche toutes les erreurs pertinentes lors de la première soumission du formulaire et supprime une erreur lorsque l'utilisateur modifie le texte dans l'élément d'entrée approprié.

Pour qu'il affiche toutes les erreurs lors de la première exécution, j'ai utilisé des instructions if au lieu de if else et un indicateur pour déterminer si le formulaire devait être soumis. Pour supprimer les avertissements lorsque l'entrée est modifiée, j'ai lié les événements onkeyup des entrées.

J'ai fini par supprimer les attributs required sur les entrées afin que la démonstration fonctionne dans un navigateur moderne les prenant en charge.

Démo en direct:

document.getElementById("english_registration_form").onsubmit = function () {
    var x = document.forms["english_registration_form"]["name"].value;
    var y = document.forms["english_registration_form"]["email"].value;
    var z = document.forms["english_registration_form"]["telephone"].value;

    var submit = true;

    if (x == null || x == "") {
        nameError = "Please enter your name";
        document.getElementById("name_error").innerHTML = nameError;
        submit = false;
    }

    if (y == null || y == "") {
        emailError = "Please enter your email";
        document.getElementById("email_error").innerHTML = emailError;
        submit = false;
    }

    if (z == null || z == "") {
        telephoneError = "Please enter your telephone";
        document.getElementById("telephone_error").innerHTML = telephoneError;
        submit = false;
    }

    return submit;
}

function removeWarning() {
    document.getElementById(this.id + "_error").innerHTML = "";
}

document.getElementById("name").onkeyup = removeWarning;
document.getElementById("email").onkeyup = removeWarning;
document.getElementById("telephone").onkeyup = removeWarning;
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
    <input type="text" id="name" name="name" aria-describedby="name-format" placeholder="Name"> <span class="error"><p id="name_error"></p></span>

    <input type="email" id="email" name="email" placeholder="Email"> <span class="error"><p id="email_error"></p></span>

    <input type="tel" id="telephone" name="telephone" placeholder="Telephone"> <span class="error"><p id="telephone_error"></p></span>

    <button class="register_button" type="submit" value="submit">Register Now</button>
</form>

Version JSFiddle: https://jsfiddle.net/xga2shec/

6

Tout d’abord, nous changeons votre fonction validateForm afin qu’elle puisse gérer plusieurs validations.

Ensuite, nous créons un gestionnaire d'événements DOMContentLoaded sur le document et appelons la fonction validateForm. Nous validons donc le champ lorsque la page est chargée.

Et pour finir, nous créons des gestionnaires d'événements input sur les entrées. Ainsi, chaque fois que quelqu'un modifie les données qu'il contient, le formulaire est à nouveau validé.

Regardez le code commenté et voyez la version de travail en action!

function validateForm() {
  var valid = true; // creates a boolean variable to return if the form's valid
  
  if (!validateField(this, 'name')) // validates the name
    valid = false;
  
  if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
    valid = false;
  
  if (!validateField(this, 'telephone')) // validates the telephone 
    valid = false;
  
  return valid; // if all the fields are valid, this variable will be true
}

function validateField(context, fieldName) { // function to dynamically validates a field by its name
  var field = document.forms['english_registration_form'][fieldName], // gets the field
      msg = 'Please enter your ' + fieldName, // dynamic message
      errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
  // if the context is the form, it's because the Register Now button was clicked, if not, check the caller
  if (context instanceof HTMLFormElement || context.id === fieldName)
    errorField.innerHTML = (field.value === '') ? msg : '';

  return field.value !== ''; // return if the field is fulfilled
}


document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
  // add event handlers when changing the fields' value
  document.getElementById('name').addEventListener('input', validateForm);
  document.getElementById('email').addEventListener('input', validateForm);
  document.getElementById('telephone').addEventListener('input', validateForm);
  
  // add the event handler for the submit event
  document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
  <input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
  <span class="error"><p id="name_error"></p></span>
  <input type="email" id="email" name="email" required placeholder="Email">
  <span class="error"><p id="email_error"></p></span>
  <input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
  <span class="error"><p id="telephone_error"></p></span>
  <button class="register_button" type="submit" value="submit">Register Now</button>
</form>

2
Buzinas

vous devez utiliser style.display="none" pour masquer l'erreur et style.display="block" pour afficher l'erreur

 <script>
    function validateForm() {
    var x = document.forms["english_registration_form"]["name"].value;
    var y = document.forms["english_registration_form"]["email"].value;
    var z = document.forms["english_registration_form"]["telephone"].value;

    if (x == null || x == "") {
        nameError = "Please enter your name";
document.getElementById("name_error").style.display="block";
        document.getElementById("name_error").innerHTML = nameError; 
        return false;
    } 
    else if (x != null || x != "") {
        nameError = "Please enter your name";
        document.getElementById("name_error").style.display="none"; 
        return false;
    } 

     if (y == null || y == "") {
        emailError = "Please enter your email";
 document.getElementById("email_error").style.display="block"; 
        document.getElementById("email_error").innerHTML = emailError;
        return false;
    } 
    else if (y != null || y != "") {
        emailError = "Please enter your email";
        document.getElementById("email_error").style.display="none"; 
        return false;
    } 

     if (z == null || z == "") {        
        telephoneError = "Please enter your telephone";
 document.getElementById("telephone_error").style.display="block"; 
        document.getElementById("telephone_error").innerHTML = telephoneError;
        return false;
    } 

     else if (z != null || z != "") {        
        telephoneError = "Please enter your telephone";
        document.getElementById("telephone_error").style.display="none"; 
        return false;
    } 

    else {return true;}
    }
    </script>
0
kavinhuh

function validateForm() {
  var valid = true; // creates a boolean variable to return if the form's valid
  
  if (!validateField(this, 'name')) // validates the name
    valid = false;
  
  if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
    valid = false;
  
  if (!validateField(this, 'telephone')) // validates the telephone 
    valid = false;
  
  return valid; // if all the fields are valid, this variable will be true
}

function validateField(context, fieldName) { // function to dynamically validates a field by its name
  var field = document.forms['english_registration_form'][fieldName], // gets the field
      msg = 'Please enter your ' + fieldName, // dynamic message
      errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
  // if the context is the form, it's because the Register Now button was clicked, if not, check the caller
  if (context instanceof HTMLFormElement || context.id === fieldName)
    errorField.innerHTML = (field.value === '') ? msg : '';

  return field.value !== ''; // return if the field is fulfilled
}


document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
  // add event handlers when changing the fields' value
  document.getElementById('name').addEventListener('input', validateForm);
  document.getElementById('email').addEventListener('input', validateForm);
  document.getElementById('telephone').addEventListener('input', validateForm);
  
  // add the event handler for the submit event
  document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
  <input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
  <span class="error"><p id="name_error"></p></span>
  <input type="email" id="email" name="email" required placeholder="Email">
  <span class="error"><p id="email_error"></p></span>
  <input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
  <span class="error"><p id="telephone_error"></p></span>
  <button class="register_button" type="submit" value="submit">Register Now</button>
</form>

0
jvk