Form Validation advice needed

Hello all JS masters,

I have two forms on my website which must be validated and I am torn between many options. After a bit of research, I am not so keen on using jquery as it only displays error messages either before or after the input fields. What I am trying to achieve is to display the error messages in a separate div which I created right next to the submit button. I have 4 fields in total (name, email, phone and message) and the only method I have tried was the onblur function. It gives user a some sort of indication of missing field but the form still submits itself. As you can tell, I am not super competent in JS so I would really appreciate your advice on how to best solve this issue. Many thanks in advance.

    document.my_form.name.onblur=function() {
    if (document.my_form.name.value==="") {
    document.getElementById('response_one').innerHTML="! Please enter your name.</br>";
    } else {
    document.getElementById('response_one').innerHTML="";    
    }
    }

Hi,

hereā€™s a simple validation script I made for someone a while back. Maybe itā€™ll help you:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Form</title>
    <style>
      form{padding: 15px}
      label{display: inline-block; text-align: right; width:60px; padding-right:5px;}
      input[type=submit]{margin-top: 20px;}
      .error{color: red; margin-left: 10px;}
    </style>
  </head>

  <body>
    <form action="" method="post" id ="aanmelden">
      <div>
        <label>Name:</label>
        <input type="text" name="name" placeholder="Name">
      </div>

      <div>
        <label>Address:</label>
        <input type="text" name="address" placeholder="Address">
      </div>

      <div>
        <label>City:</label>
        <input type="text" name="city" placeholder="City">
      </div>

      <input type="submit" />
    </form>

    <script>
      function removeElementsByClass(className){
        elements = document.getElementsByClassName(className);
        while(elements.length > 0){
          elements[0].parentNode.removeChild(elements[0]);
        }
      }

      function flagError(field, prependText){
        var message = prependText + " cannot be left blank";
        form[field].insertAdjacentHTML('afterend', '<span class="error">' + message + '</span>');
      }

      function checkEmpty(field, prependText){
        if (form[field].value === ""){
          flagError(field, prependText);
          isValidSubmission = false;
        }
      }

      function validateForm() {
        removeElementsByClass("error");

        checkEmpty("name", "First name");
        checkEmpty("city", "City");
        checkEmpty("address", "Address");

        return isValidSubmission;
      }

      var form = document.getElementById("aanmelden"),
          isValidSubmission = true;

      form.onsubmit = validateForm;
    </script>
  </body>
</html>

Hereā€™s a demo.

2 Likes

There are a few different ways to validate a form. If I may make one suggestion, though. Donā€™t use an alert on each blur - that can become quite annoying to the user.

Create a validation function that will be called upon the form submit, one that will declare a variable and set it to blank, then for each field that doesnā€™t pass muster add text and a line break character. Then, at the end of the function, if the variable is empty, all fields are correct, empty the error element of all text and submit the form - but if the variable isnā€™t empty, populate the error element with the data in the variable and return false so the form doesnā€™t submit.

Just my two cents plus inflation.

HTH,

:slight_smile:

2 Likes

Here is complete solution for you: http://jsfiddle.net/vwk0L7cb/1/
Feel free to use that code

1 Like

It accepts ā€œasdfā€ as a phone number. Some additional validation is needed. That was just the first field I tried to break.

1 Like

Thanks @James_Hibbard

@WolfShade will keep these in mind. Thanks.

@megazoid This is pretty close to what I had in mind. Many thanks.

@RyanReese Thanks for the heads up Ryan.

Hello @megazoid,

The last field on my form is not an input field but a text area. Your foreach function is only looping through the input fields. How can I add the text area to the loop?

If you do come back to considering using the jQuery validator, it can easily place the errors in your error label container. With a bit of further research a full and complete solution can be put together.

Modified version with textarea: http://jsfiddle.net/vwk0L7cb/2/

2 Likes

Thank you so much. It works great.

Hello Megazoid,

I have one last question for you. Can I use this script another form on the same page. I have two forms but only one of them is visible at a time (I put them in a slider) if I wanted to use this script for the second form, what should I modify?

I have tried changing the class of submit button for the second form and duplicated the script but that did not work. I would really appreciate if you could spare your opinion on this.

Many thanksā€¦

Modified version to handle multiple forms: http://jsfiddle.net/vwk0L7cb/5/

1 Like

Man you are a life saver. Thank you so muchā€¦

Hello again,

I wanted to ask you one last question if you donā€™t mind. Does .parent selector only work when all the elements placed inside the same div? For example when I place the submit button into a right aligned div and error window into a left aligned div, the script doesnā€™ t work. However, when I put all of them into the same div, it just works fine.

I am using Foundation5 by the way, to layout the elements I need to use separate columns.

This is my code with both forms inside.

form.html (4.3 KB)

Ok, here is next modified version: http://jsfiddle.net/vwk0L7cb/6/

Iā€™ve added id to each form:

<form id="first-form" ...>

and data-form attribute to each submit button that points to corresponding form:

<input type="submit" data-form="first-form" ... />

Hi there,

I have also come up with a solution. Instead of .parent(ā€˜formā€™); I used .parents(ā€˜formā€™);

I am not sure if that is the best way to accomplish what I want but it seems to fix the issue.

I am also bookmarking your answer just in case I may need it in the future. You have been a great help. Thank a lot.

Hi,

I guess .each is only looping the input fields but omitting the select fields. Even though I set required attribute for select fields, they are still not getting included in the errors array. Is there a quick fix for this?

I found a solution. I just set the values of select fields to ā€œā€ and it worked fine. It was ā€œdefaultā€ before.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.