简体   繁体   中英

Simple Form Validation to Check Empty Inputs and Display Message

I'm attempting a simple form validation where if the input field is empty, the user will see a message asking to fill out any fields that are empty.

I'm able to loop and find which fields are empty and display a message, but the message will only display the last input field that was looped. How do I get the message to display all input fields that are empty?

HTML:

<label>Name</label>
<input class=formInput" name="name" />

<label>Email</label>
<input class=formInput" name="email" />

<label>Message</label>
<textarea class=formInput" name="message" />

<span id="fail-message"></span>

JS:

let inputFields = document.getElementsByClassName('formInput');

for (var i = 0; i < inputFields.length; i++) {
  if (inputFields[i].value === '') {
    document.querySelector('#fail-message').innerHTML =
      'Please fill out ' +
      inputFields[i].getAttribute('name') +
      ' field(s)';
  }
}

This currently outputs "Please fill out message field(s)"

Assuming all is empty, I'd like it to output "Please fill out name, email and message field(s)"

The code you have overwrites the innerHTML completely every time it finds an empty field. What you should do instead is keep an array of all the empty fields, then only write the innerHTML once after the loop, with the list of fields it found.

let inputFields = document.getElementsByClassName('formInput');
const emptyFieldNames = [];

for (var i = 0; i < inputFields.length; i++) {
  if (inputFields[i].value === '') {
    emptyFieldNames.push(inputFields[i].getAttribute('name'));
  }
}
if (emptyFieldNames.length > 0) {
    document.querySelector('#fail-message').innerHTML = 'Please fill out the following fields: ' + emptyFieldNames.join(', ');
}

You overwrite the innerHTML of the message span in every iteration. You should concatenate the new error to it or use separate spans.

You would have to build an array containing the fields name that are not valid ... right now, you "overwrite" the innerHTML of the #fail-message element with the latest field (aka, it is INSIDE your loop to be rewritten each time the condition is met in the loop).

Add the names of the field in array (do not rewrite the whole array) and then use "yourArray.join()" to output all the names in the innerHTML of the correct element, like you do inside your loop.

You are replacing the value in the span element everytime you go through the loop. So only the last empty form element will be shown as fail message. Instead, you have to concatenate each string and then show it together.

Here is the complete code that will work for you:

<html>
<head>
    <script>
        function myFunction() {
            let inputFields = document.getElementsByClassName('formInput');
            let message =''; 
            for (var i = 0; i < inputFields.length; i++) {
                console.log(inputFields[i].value);
                if (inputFields[i].value === '') {
                        message = message + inputFields[i].getAttribute('name') + ', ';
                }
            }

            let n = message.lastIndexOf(",");
            message = message.substring(0,n); 

            document.querySelector('#fail-message').innerHTML =
                'Please fill out ' +
                message +
                ' field(s)';
        }
    </script>
</head>

<body>
    <label>Name</label>
    <input class="formInput" name="name" />

    <label>Email</label>
    <input class="formInput" name="email" />

    <label>Message</label>
    <textarea class="formInput" name="message"> </textarea>

    <button onclick="myFunction()">Submit</button>

    <span id="fail-message"></span>
</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM