最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Individual error messages for empty form fields using JavaScript - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Sep 22, 2015 at 4:32 Maximillian Laumeister 20.4k10 gold badges61 silver badges83 bronze badges asked Sep 22, 2015 at 4:15 SophieSophie 831 gold badge1 silver badge6 bronze badges 1
  • In my opinion you can put the errors strings hard-coded in the HTML error spans with style="display:none;" (hide them), and then, when needed - show them (remove the above style for relevant span). Next, add this function to 'onchange' event rather than on submit – ItayB Commented Sep 22, 2015 at 4:23
Add a comment  | 

4 Answers 4

Reset to default 9

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/

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>

you have to use style.display="none" to hide error and style.display="block" to show error

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

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)

  1. 暂无评论