Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Individual error messages for empty form fields using JavaScript

I need to validate my form using JavaScript because iPhone / Safari do not recognize the required attribute. I want individual error messages to appear below each empty input field.

My code works, but the individual error message does not disappear when the field is filled in. Also, I would like all messages to appear initially, for all empty fields (not one by one). I am very very new to JavaScript, sorry.

My 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>

And my 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>

Thanks for your help.

like image 749
Sophie Avatar asked Sep 22 '15 04:09

Sophie


People also ask

How do you show error message in form?

In order to display error messages on forms, you need to consider the following four basic rules: The error message needs to be short and meaningful. The placement of the message needs to be associated with the field. The message style needs to be separated from the style of the field labels and instructions.

How do you display error message below input field in HTML?

To customize the appearance and text of these messages, you must use JavaScript; there is no way to do it using just HTML and CSS. HTML5 provides the constraint validation API to check and customize the state of a form element. var email = document. getElementById("mail"); email.


2 Answers

Here is a solution that displays all relevant errors when the form is first submitted, and removes an error when the user modifies text in the relevant input element.

To get it to display all of the errors on first run, I used if statements instead of if else, and used a flag to determine whether the form should be submitted. To remove the warnings when the input is modified, I bound the onkeyup events of the inputs.

I ended up removing the required attributes on the inputs so that the demonstration will work in a modern browser that supports them.

Live Demo:

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>

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

like image 133
Maximillian Laumeister Avatar answered Sep 21 '22 16:09

Maximillian Laumeister


First of all, we change your function validateForm so it can handle multiple validations.

Then, we create a DOMContentLoaded event handler on the document, and we call the validateForm function, so we validate the field when the page is loaded.

And to finish, we create input event handlers on the inputs, so everytime someone change any data inside them, the form is validated again.

Take a look at the code commented, and see the working version in 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>
like image 37
Buzinas Avatar answered Sep 19 '22 16:09

Buzinas