Simple JavaScript Form Validation

Today I wanted to write a quick demonstration of how to do a very simple client side form validation.

There are two types of form validation, server-side and client side, today we will cover client side validation with JavaScript.

Example of simple form validation (Click Submit)



Ok lets start with a blank document:





Simple Form Validation


%MINIFYHTML1b7458cc01c11dd74eb0333bb7d85e645%%MINIFYHTML1b7458cc01c11dd74eb0333bb7d85e646%%MINIFYHTML1b7458cc01c11dd74eb0333bb7d85e647%

In your body tags add the following simple form:







Ok first thing to point out with our simple form is that the form tag its self. The form tag has a on submit event of “return validate();” that is awaiting the return of either true or false from the function validate().

The second thing I would like to point out is that we gave our form a name of “simpleForm”. We give our form a name so that we can reference to it much quicker in our JavaScript “validate()” function that we will cover here in a second.

Moving onto the actual JavaScript, add the following to your documents header tags:

%MINIFYHTML1b7458cc01c11dd74eb0333bb7d85e648%

Great, here we are forming our validate() function and in this function we are going to create a simple condition that checks each of our form fields to validate if their values are empty or not.

Lets point to our first form element like so:

%MINIFYHTML1b7458cc01c11dd74eb0333bb7d85e649%

We first point to our document, then to the name of our form “simpleForm”, and then to the name of our first form element “firstName”. Once we are pointing to the first form element, we check its value to see if indeed its value is empty or not (== “”).

Its that simple!

Now lets point to the other two form elements (lastName and message) to bring validation them as well. We can extend our conditional statement to the rest of our form elements by using whats called “Logical Operators” like so:

%MINIFYHTML1b7458cc01c11dd74eb0333bb7d85e6410%

Notice how we are using the “||” between each form elements we point to? Basically we are saying “if firstName element value is equal to empty, OR (||) lastName element is equal to empty, OR (||) message element is equal to empty, then do the following”.

By using the “||” OR logical operators we can extend our condition to as many form elements as we like. There are more logical operators that you can read about here.

Great so now that we have extended out validation condition to check our three elements value’s, lets move on to the part of the function that cancels the form from being submitted if indeed one or more form element is empty like so:

function validate(){
    if(document.simple_form.firstName.value == "" ||
    document.simple_form.lastName.value == "" ||
    document.simple_form.message.value == "")
    {
        alert("Please fill out all fields before clicking submit!");
        return false;
    }
}

The first thing we want to do is inform the user that we must have all form elements filled out before it will be submitted. We do this by using the JavaScript altert to send our reminder to the user. Next we use “return false;” after altering our message to stop the form submitting and allow the user to correct their error.

And that’s it!

So with our simple condition we have pointed to each of our forms elements and peeked at its value. If the value of any of our form elements is equal to empty or rather nothing, we begin to alert a reminder to the user and halt the form from submitting to allow the user to correct the error. If all form fields pass our simple validation condition then our form continues to submit as normal.

Thanks everyone.

Devin R. Olsen

THE BELOW FORM IS NOT A DEMO!!

Devin R. Olsen

Located in Portland Oregon. I like to teach, share and dabble deep into the digital dark arts of web and game development.

More Posts

Follow Me:
TwitterFacebookGoogle Plus

42 Responses to “Simple JavaScript Form Validation”

  1. Jimmie says:

    An impressive share! I have just forwarded
    this onto a colleague who has been doing a little homework on this.

    And he actually ordered me lunch due to the fact that I stumbled upon it
    for him… lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanks for spending some time to talk about
    this topic here on your web page.

  2. buji says:

    thanks its useful for me

  3. malikatiq says:

    plz tell me about email validation in form

  4. Andy says:

    dear kami for the knowing that where this message will store you have to learn database.

  5. anthony says:

    This article was very useful. My form though has four submit buttons. Save,update,delete and load. I want the code to only have an effect on my save button while the other buttons does not return a validation. How do I do that. I am new to the world of programming

  6. iRocketEli says:

    I usually don’t comment on things, but I just wanted to say I was looking for a simple solution for form validation, and this was super easy to implement, Thanks mate!

  7. Vinit says:

    Hey,

    I tried using the code and works fine using Firefox but doesn’t seem to be working when using Google Chrome?

    Any ideas?

  8. Kedar says:

    Its So Simple but Useful for Begineers

  9. Kartavya Desai says:

    It is very helpful to me but i want more material on validation which make me very familier with validation and make me easy with it….Can you give me such kind of material…?

  10. gladys says:

    wow!!!this is amazing!:)

  11. Shejuti says:

    Hi Devin,
    I’m a beginner, so having huge problem with codes.
    You put your web address into the action, then how is it connecting to the javascript file?
    the html part is working well,bt no alert is appearing. I mean the javascript file is not working.

  12. Sam says:

    Really helpful tutorial – the first one I’ve found that worked first time!

    Can you use this to validate dropdown menus, checkboxes or radio buttons?

  13. Ruby says:

    I want to use min length 0-8 characters in my form but it is not working .Please tell me the solution.

  14. hello says:

    hello Devin, How can i limit the characters they type?

    heres my code i dont know if its correct (beginner here ^^ )

    function validateForm()
    {
    if (document.myForm.fullname.value > 25 || document.myForm.username.value > 25 )
    {
    alert(“max limit for username and full name are 25 characters!”);
    return false;
    }
    }

    pls correct me :)

  15. Gerald says:

    Devin, unless I’m missing something in the text I believe there is an error in the bottom shaded box in the validation function where you drop in the alert. I see:

    if(document.simple_form.firstName….

    rather than

    if(document.simpleForm.firstName…

    I couldn’t figure out why the snippet I copied from there wasn’t working properly but I believe that’s it.

  16. Howard says:

    Hi,
    I need a lot of hand-holding and this whole forms validation thing is making me nuts. I really appreciate your approach to instructing, it looks like what I need and I will be bookmarking your site.

    However,(isn’t there always one?) The simple form validation example is not working. I leave all fields empty and it apparently submits anyway.

    I have copied and pasted in order to avoid mistakes. The only change made was to direct form action to my starfire engraving site.

    In the script, the phrase ‘return false;’ is italic and a different color. In my limited experience, that usually means something’s not right…but I can’t see it. (Again, cut and pasted from the instructions).

    Help?

  17. navin israni says:

    really simple explanation!! very nice…it almost felt I am attending a lecture by Prof. Devin Olsen :D

  18. subash says:

    Its very useful beginer . thank you devin

  19. usagi-chan says:

    Fantastic! Just what I was looking for. Thank you so much. :)

  20. prakash says:

    if i can hide the javascript in the browser…wt u do..In that time java script work or not?! ;)

  21. Marion Ayala says:

    Found you on Yahoo, exactly what I was looking for! :)

  22. jigar 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?

    Wow! It’s really very good…

  23. 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?

  24. Solange says:

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

  25. crystal says:

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

  26. caspersky says:

    its good

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

  28. Adam says:

    How do you get it to load the comment?

  29. Adam says:

    Well, I’m testing it

  30. mustajab says:

    Wow! It’s really very good…

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

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

  33. Shakeel says:

    very nice tutorial Thanks Devin

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

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

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

  37. 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!

  38. 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?

  39. Devin R. Olsen says:

    I always enjoy feedback from my readers!

Leave a Reply