Simple JavaScript Form Validation

Today I wanted to write a quick demonstration of how to do a simple form validation. Here you will learn how to make sure that certain form fields are filled before any data is allowed to be sent off.

Example of simple form validation (Click Submit)

There are two types of form validation, server side and client side. Today we will cover client side or rather pre-sent form data.

Ok lets start with a blank document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
</body>
</html>

In your body tags add the following simple form:

<form action="" method="" onsubmit="return validate()">
    <label>First Name:</label>
    <input type="text" class="validate" />    <br />
    <label>Last Name:</label>
    <input type="text" class="validate" />
    <br />
    <br />
    <label>Comment:</label>
    <br />
    <textarea class="validate" style="width:400px; height:120px;"></textarea>
    <br />
    <br />
    <input type="submit" value="Submit" style="margin-left:345px;" />
</form>

Ok first think to point out with our simple form is that the form tag its self has a on submit of “return validate()”. This on submit rule is awaiting the return of either true or false from the function validate(). We will cover this “validate()” function here in a second.

Next notice that we have three input tags each with a class of “validate“? These input elements are going to be validated over our JavaScript function because of the use of this class name.

Ok lets move onto the actual JavaScript shall we. Add the following to your documents header tags:

<script type="text/javascript">
function validate()
{
  var valid = document.getElementsByClassName("validate");
  for(var i=0;i<valid.length;i++)
  {

  }
}
</script>

Great, here we are forming our validate() function. In this function we are going to collect all the form fields that have a class of “validate” into the variable called “valid”.

Next we are going to perform a JavaScript for loop to being looping over each found element with a class of “validate“. The for loop simple creates a temporary variable called “i” and equals it to “0“. The for loop then uses a less than condition to state if “i” is less than our “valid” variables amount of found elements then keep looping. .length is a native JavaScript call to find the count or number of elements or text. i++ is also another native JavaScript call that takes our variable “i” and continues a count or in our case loop.

Next lets begin to perform our simple validation or rather foor loop condition for each found element with the class of “validate“. Update your JavaScript with this new code.

<script type="text/javascript">
function validate()
{
  var valid = document.getElementsByClassName("validate");
  for(var i=0;i<valid.length;i++)
  {
    var element = valid[i].value;
    var stripElement = element.replace(/ /g,"");
  }
}
</script>

Great what we have done now is create two very important variables for our loop condition. The first variable is named “element” this is equaling its self to “valid[i]“. Valid is the name of our looped class and [i] represents the current element count in the loop. There for the new variable “elements” is capturing the looped element into a variable that we can make use of. Last we point to the value attribute of the form field element to gather any characters or text the user has imputed.

Our next new variable is named “stripElement” and it first equals its self to our new variable “element” but then uses another native JavaScript call “replace“. The replace feature will strip any spaces out of the elements to only make up real characters to validate user input. How the replace works is it takes two arguments if you will, one to identify what to replace and the other is what our first will be replaced with. So / /g states “Any spaces found globally in this elements value or string of text, replace it with “” or rather nothing.”

Again the reason we strip any spaces from found characters or text the users input is to eliminate any users error by only imputing a single or more amount of spaces but no text.

Great lets keep going and add our validation conditions now that we have our two needed variables. Update your script with the following:

<script type="text/javascript">
function validate()
{
  var valid = document.getElementsByClassName("validate");
  for(var i=0;i<valid.length;i++)
  {
    var element = valid[i].value;
    var stripElement = element.replace(/ /g,"");
    if(stripElement.length > 0){
    } else {
      valid[i].style.background="#FF0000";
      alert("Sorry but there seems to be a problem with your submission, please check over the form again.");
      return false;
    }
  }
}
</script>

Ok for our error output we first state “valid[i]” (our current element in the loop), “style“(the elements style attribute),”background“(the elements background style) and equal it to a web safe red. What this will do is if the form field has not passed our simple validation it background color will change to red to give our user and indicator of where they error lays.

Next we alert our error message out to the user as well to prompt them they may need to look over the form once more.

Last we use a return of false, we do this so we may halt any further of the form submission any further because we have an error result.

Ok now that we have finished our error validation portion of our looped condition and halted any further of the form submission when errors occurs is only logical we must also give a return of when everything is valid over all our form field elements. The return true will allow our form to continue its submission once everything has been check and validated over our simple form validation function. Update your script with the following:

<script type="text/javascript">
function validate()
{
  var valid = document.getElementsByClassName("validate");
  for(var i=0;i<valid.length;i++)
  {
    var element = valid[i].value;
    var stripElement = element.replace(/ /g,"");
    if(stripElement.length > 0){
    } else {
      valid[i].style.background="#FF0000";
      alert("Sorry but there seems to be a problem with your submission, please check over the form again.");
      return false;
    }
  }
  return true;
}
</script>

And that’s it everyone, told you it was simple.

Thanks.

Devin R. Olsen

THE BELOW FORM IS NOT A DEMO!!

This Article's Comments.

  1. 19
    DIY Makeup Says:

    Hi sweetie, sweet website! I really like this post.. I was curious about this for a long time now. This cleared a lot up for me! Do you have a rss feed that I can add?

  2. 18
    Solange Says:

    Thanks for your support, i love your article for beginners. I never comment on those blogs, even when the content is great

  3. 17
    Devin R. Olsen Says:

    I always enjoy feedback from my readers!

  4. 16
    kami Says:

    thaks
    but i want to know that, where is this message will send?
    i couldnt find any email address in the source
    when user push sumbit what happend next?

  5. 15
    Devin R. Olsen Says:

    Hi kami, I assume you are talking about what happens to the data in the above example if all fields are valid and filled with data and you click submit. In this example the data is not being handled by any server side function so you only receive a page refresh as if the data was to be sent off to a server side function. Of course if you are speaking of how to preform a server side function with form data. That would be another tutorial and one that’s coming up very soon!

  6. 14
    kami Says:

    thanks for ur answers
    but i wonder if i do this kind of things with clien side method
    i mean i want to set an emial address that info send to it

  7. 13
    santiago Says:

    how do you make the message go to your email. Could you email me the code or give me a link to a tutorial plz. Tanks

  8. 12
    Devin R. Olsen Says:

    Casting information to an email address with client side code such as JavaScript is not possible alone. You must also use a server side language such as PHP or ASP to perform a message send from one domain to another.

    I don’t have any tutorials here yet but I know there are quite a few out there on PHP’s version.

  9. 11
    Shakeel Says:

    very nice tutorial Thanks Devin

  10. 10
    Shakeel Says:

    Can u please give me some piece of code for Comments same you are using, Name and comment field, and directly publish to website, i dont wana need to have user attentications or making acount and no more checks needed for this comment field.. I shall be greatful to you shakeelakbar1@yahoo.com

  11. 9
    Devin R. Olsen Says:

    Hi Shakeel, I assume you are talking about the comment box I have on all my tutorials. I am using both AJAX and PHP/MySQL to perform the seamless comment posting. I would be more than happy to write up a tutorials on this vs. sending you the code. This way any unanswered questions you or many other might have will be answered in one spot. Please check back here with in the next day or so under tutorials/AJAX.

  12. 8
    amanuel Says:

    a is best

  13. 7
    m. Says:

    .k.n

  14. 6
    mustajab Says:

    Wow! It’s really very good…

  15. 5
    Adam Says:

    Well, I’m testing it

  16. 4
    Adam Says:

    How do you get it to load the comment?

  17. 3
    Devin R. Olsen Says:

    @Adam, this tutorial covers how to do a simple form validation. Meaning it checks to see if form fields are not filled out. This is not a tutorial on how to do a comment box like I have here on the site. Until I release the tutorial on how to do so, you m

  18. 2
    caspersky Says:

    its good

  19. 1
    crystal Says:

    this page is not working – i even used all your work, it does not bring up alerts!

Leave a Reply