• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / Form Validation with JavaScript

Form Validation with JavaScript

17 October 2001 / 75 Comments

This tutorial will show you how to create a JavaScript-enabled form that checks whether a user has filled in the form correctly before it’s sent to the server. This is called form validation. First we’ll explain why form validation is a useful thing, and then build up a simple example form, explaining things as we go along. At the end, there’s a little exercise to keep you busy too!

What is form validation?

Form validation is the process of checking that a form has been filled in correctly before it is processed. For example, if your form has a box for the user to type their email address, you might want your form handler to check that they’ve filled in their address before you deal with the rest of the form.

There are two main methods for validating forms: server-side (using CGI scripts, ASP, etc), and client-side (usually done using JavaScript). Server-side validation is more secure but often more tricky to code, whereas client-side (JavaScript) validation is easier to do and quicker too (the browser doesn’t have to connect to the server to validate the form, so the user finds out instantly if they’ve missed out that required field!).

Client-side validation
Client-side form validation (usually with JavaScript embedded in the Web page)
Server-side validation
Server-side form validation (usually performed by a CGI or ASP script)

In this tutorial we’ll build a simple form with client-side JavaScript validation. You can then adapt this form to your own requirements.

A simple form with validation

Let’s build a simple form with a validation script. The form will include one text field called “Your Name”, and a submit button. Our validation script will ensure that the user enters their name before the form is sent to the server.

Open this page to see it in action. Try pressing the Send Details button without filling anything in the “Your Name” field.

You might like to open the source code for this form in a separate window, so that you can refer to it throughout the tutorial.

You can see that the page consists of a JavaScript function called validate_form() that performs the form validation, followed by the form itself. Let’s look at the form first.

The form

The first part of the form is the form tag:


<form name="contact_form" method="post"
action="/cgi-bin/articles/development/
  javascript/form-validation-with-javascript/contact_simple.cgi"
onsubmit="return validate_form ( );">

The form is given a name of "contact_form". This is so that we can reference the form by name from our JavaScript validation function.

The form uses the post method to send the data off to a dummy CGI script on ELATED.com’s server that thanks the user. In reality, you would of course send the data to your own CGI script, ASP page, etc. (e.g. a form mailer).

Finally, the form tag includes an onsubmit attribute to call our JavaScript validation function, validate_form(), when the “Send Details” button is pressed. The return allows us to return the value true or false from our function to the browser, where true means “carry on and send the form to the server”, and false means “don’t send the form”. This means that we can prevent the form from being sent if the user hasn’t filled it in properly.

The rest of the form prompts the user to enter their name into a form field called contact_name, and adds a “Send Details” submit button:


<h1>Please Enter Your Name</h1>

<p>Your Name: <input type="text" name="contact_name"></p>
<p><input type="submit" name="send" value="Send Details"></p>

</form>

Now let’s take a look at the JavaScript form validation function that does the actual work of checking our form.

The validate_form() function

The form validation function, validate_form(), is embedded in the head element near the top of the page:


<script type="text/javascript">
<!--

function validate_form ( )
{
    valid = true;

    if ( document.contact_form.contact_name.value == "" )
    {
        alert ( "Please fill in the 'Your Name' box." );
        valid = false;
    }

    return valid;
}

//-->
</script>

The first line (<script type="text/javascript">) tells the browser that we are writing some JavaScript, and the HTML comment (<!--) in the second line hides the script from older browsers that don’t understand JavaScript.

Next we start our validate_form() function, then set a variable called valid to the value true:


function validate_form ( )
{
    valid = true;

We use this valid variable to keep track of whether our form has been filled out correctly. If one of our checks fails, we’ll set valid to false so that the form won’t be sent.

The next 5 lines check the value of our contact_name field to make sure it has been filled in:


    if ( document.contact_form.contact_name.value == "" )
    {
        alert ( "Please fill in the 'Your Name' box." );
        valid = false;
    }

If the field is empty, the user is warned with an alert box, and the variable valid is set to false.

Next, we return the value of our valid variable to the onSubmit event handler (described above). If the value is true then the form will be sent to the server; if it’s false then the form will not be sent:


    return valid;

Finally, we finish our validate_form() function with a closing brace, and end our HTML comment and script element:


}

//-->

</script>

That’s all there is to simple JavaScript form validation! Our example is very simple as it only checks one field. Let’s expand this example with a more complex function that checks lots of form fields. We’ll also look at how to check other types of fields, such as checkboxes, radio buttons and drop-down lists.

A more complex form

Let’s look at a more complex validated form with some different types of form fields.

Open this page to see it in action. Try pressing the Send Details button without filling in the form and see what happens.

Again, you might like to open the source code for this form in a separate window, so that you can refer to it as we talk you through.

Like our previous example, this page has a form called contact_form and a function called validate_form(). In addition to the previous text field, the form has radio buttons, a drop-down list and a checkbox.

The validate_form() function now has 3 extra checks, one for each of our new fields.

Validating radio buttons

After the contact_name text box has been checked, the gender radio buttons are validated:


    if ( ( document.contact_form.gender[0].checked == false )
    && ( document.contact_form.gender[1].checked == false ) )
    {
        alert ( "Please choose your Gender: Male or Female" );
        valid = false;
    }

This code checks to see whether either of the radio buttons (“Male” or “Female”) have been clicked. If neither have been clicked (checked == false), the user is alerted and valid is set to false.

Validating drop-down lists

Next the “Age” drop-down list is checked to see if the user has selected an option. In the form, we named the first option in the drop-down list "Please Select an Option". Our JavaScript can then check which option was selected when the user submitted the form. If the first option is selected, we know the user has not selected a “real” option and can alert them:


    if ( document.contact_form.age.selectedIndex == 0 )
    {
        alert ( "Please select your Age." );
        valid = false;
    }

Note that the values for selectedIndex start at zero (for the first option).

Validating checkboxes

Finally, the “Terms and Conditions” checkbox is validated. We want to the user to agree to our imaginary Terms and Conditions before they send the form, so we’ll check to make sure they’ve clicked the checkbox:


    if ( document.contact_form.terms.checked == false )
    {
        alert ( "Please check the Terms & Conditions box." );
        valid = false;
    }

Because we set our valid variable to false in any one of the above cases, if one or more of our checks fail, the form will not be sent to the server. If the user has not completed more than one field, then they will see an alert box appear for each field that is missing.

Now you know how to write a form validation script that can handle multiple form fields, including text boxes, radio buttons, drop-down lists and check boxes!

One point to note about JavaScript validation is that it can always be circumvented by the user disabling JavaScript in their browser, so for secure validation you’ll need to write your validating code in your server-side scripts. However, for day-to-day use JavaScript is a quick and easy way to check over your forms before they’re sent to your server.

An exercise: “one field at a time” validation

Our example script works by validating all the form fields at once. This can be a bit confusing for the user, especially if they’ve missed out more than one field, as they will get lots of alert boxes appearing and they might forget which fields they need to fill in!

As an exercise, try modifying the script to only prompt the user one field at a time. For example, if they miss out the “Name” and “Gender” fields and press “Send Details”, it will only prompt them for the “Name” field initially. Then, after they fill in the “Name” field and press “Send Details” again, it will prompt them for the “Gender” field.

As a finishing touch, try making the script move the cursor to the field that needs filling in each time (Hint: use the focus() method to do this).

Good luck!

Filed Under: JavaScript Tagged With: form checking, html, java script, onsubmit

Reader Interactions

Comments

  1. bulevardi says

    16 April 2010 at 6:19 am

    Hi,

    I changed the code a little to invoke it with the theclicker ID, this way:

    html:

    <form name="form-validate" method="post" action="">
        <input type="text" name="name" />
        <input type="text" name="email" />
        <input type="submit" name="reg" value="Done" id="theclicker">
    </form>
    

    JS:

    function restValidation() {
        valid = true;
        if ( document.form-validate.name.value == "" )
        {
            alert ( "Please fill in the 'Your Name' box." );
            valid = false;
        }
        return valid;
    }
     
    function doValidation(){
    var send = document.getElementById('theclicker');
    send.onclick = restValidation;
    }
      
    window.onload = doValidation;
    

    But I was wondering if you can’t do it without the “valid” stuff: this way:

    function restValidation() {
        if ( document.form-validate.name.value == "" )
        {
            alert ( "Please fill in the 'Your Name' box." );
         }
    }
    

    And second, if used with the valid stuff in, shouldn’t it be declared first with
    var valid = true;

    (I’m just a javascript beginner, but learning how to, the article was very handy !)

    Reply
  2. matt says

    20 April 2010 at 6:35 am

    Hey bulevardi, thanks for your response.

    I think if you missed out the “valid” stuff – particularly “return valid;” – then the form would always submit, even if it was invalid. You need to return false if the form is invalid so that it doesn’t submit.

    Declaring variables with var is optional in JavaScript; however if you don’t declare a variable with var inside a function then the variable will be global, rather than local. So you’re right – it would be a good idea to declare the variable with var in this case (although for small scripts it probably doesn’t matter).

    Hope that helps! Feel free to ask if you have any more JavaScript questions.

    Reply
  3. jmlrose18 says

    25 April 2010 at 6:59 pm

    Thank you so much for this post. I was having a lot of trouble with this until I found this. 🙂

    Reply
  4. matt says

    30 April 2010 at 5:27 pm

    @jmlrose18: You’re welcome – I’m glad the article helped. 🙂

    Reply
  5. redesignsoft says

    2 June 2010 at 11:48 am

    You can use

    onblur="validate(document.formName.fieldName.value) ;"
    

    to can check filed in database after you complete it

    Reply
  6. heshan says

    30 July 2010 at 11:06 am

    Hi,

    I want to know how can this form validations extend to check several other features such as validity of an email address, names can be only strings etc.

    Thank you,
    Heshan.

    Reply
  7. matt says

    1 August 2010 at 5:21 pm

    @heshan: Here’s how to validate an email address:

    function validateEmail ( f ) {
      if ( isEmail ( f.email_address.value ) == false )
      {
        alert ( "Please enter a valid email address." );
        f.email_address.select ( );
        return false;
      }
      return true;
    }
    
    function isEmail ( string ) {
      if ( string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1 )
        return true;
      else
        return false;
    }
    
    ...
    
    <form method="post" action="script.php" onsubmit="return validateEmail(this)"> ... </form>
    
    Reply
  8. heshan says

    1 August 2010 at 8:03 pm

    Thanks for the coding,

    But I have a problem. The email validation cannot be used with other validations. If name field is empty the system says “please enter the name”, likewise all the validations are there. When this email validation code enters nothing works properly.Is there a way to handle this problem??

    Heshan,

    Reply
  9. matt says

    1 August 2010 at 8:31 pm

    @heshan: Hard to tell without seeing your code, but you’ll probably need to write a validate() function to validate all your form fields. You can then call validateEmail() from within that function. Then set validate() to be the submit event handler for the form:

    <form method="post" action="script.php" onsubmit="return validate(this)"> ... </form>
    

    If you’re not that familiar with JavaScript then a jQuery plugin like this could save you a lot of time & effort:

    http://docs.jquery.com/Plugins/Validation

    Reply
  10. heshan says

    1 August 2010 at 8:59 pm

    This my original validation code.
    Please check and see how could it change?

    function Validate()
    {
        if (document.form1.first_name.value == '') 
        {
            alert('Please fill in your first name!');
            return false;
        }
    	else if (document.form1.last_name.value == '') 
        {
            alert('Please fill in your last name!');
            return false;
        }
        else if (document.form1.email.value == '') 
        {
           alert('Please fill in your email address!');
           return false;
        }
    	
    	else if (document.form1.phone_number.value == '') 
        {
            alert('Please fill in your phone number!');
            return false;
        }
    	else if (document.form1.user_type.value == '') 
        {
            alert('Please fill in your relevant user type!');
            return false;
        }
    	
    	else if (document.form1.username.value == '') 
        {
            alert('Please fill in your relevant username!');
            return false;
        }
        else if (document.form1.password.value == '') 
        {
           alert('Please fill in your desired password!');
          return false;
    	}
    	
    	
         
        else if (document.form1.password_confirmation.value == '') 
        {
           alert('Please fill in your password again for confirmation!');
          return false;
        }
        else if (document.form1.password.value != 
        document.form1.password_confirmation.value) 
        {
            alert("The two passwords are not identical! "+
            "Please enter the same password again for confirmation");
            return false;
        }
        	
         else{
    		 alert('You are successfully registered');
    	 }
    }
    

    ……

     <input type="submit" name="submit" value="Register User" onClick="return Validate();" class="attribute1" />
    

    Thanks,
    Heshan.

    Reply
  11. matt says

    2 August 2010 at 4:52 am

    @heshan: Here’s the general idea:

      } else if ( isEmail ( document.form1.email_address.value ) == false ) {
        alert ( "Please enter a valid email address." );
        return false;
      } else {
        alert('You are successfully registered');
    

    etc…

    Also I would set Validate() as the ‘submit’ handler for the form, rather than the ‘click’ handler for your submit button. There’s more than 1 way to submit a form. 😉

    Reply
  12. heshan says

    2 August 2010 at 10:43 pm

    Thank you very much, it really works perfectly.. 🙂

    Likewise i also want to know how can we check the validity of a name containing string characters only.

    Thanks,
    Heshan

    [Edited by heshan on 02-Aug-10 22:44]

    Reply
  13. matt says

    4 August 2010 at 1:46 am

    @heshan: You can use a regular expression for that:

      } else if ( !document.form1.email_address.value.match( /^[a-zA-Z]+$/ ) )  ) {
        alert ( "Please enter letters only." );
        return false;
      } else {
    ...
    
    Reply
  14. heshan says

    4 August 2010 at 5:44 am

    Thank you very much for your help 🙂

    Reply
  15. matt says

    4 August 2010 at 6:16 am

    @heshan: No problem. 🙂 Feel free to ask if you have any more questions!

    Reply
  16. kirand says

    9 August 2010 at 8:59 am

    Hi
    I have a bunch of required text fields and I could not figure out how to move the cursor to the first missed required text field in the form.

    Appreciate your time and help.
    Thanks,
    Kiran

    Reply
  17. kirand says

    9 August 2010 at 3:01 pm

    I could figure achive focusssing on the missed field that is required. But the problem now is it works fine in FF but not in IE.
    When I submit the form the first time with missed required fields, it focusses on the first but the second time I miss a field it does not focus on the field.

    I tried using setTimeout , but doesn’t seem to help much.

    Appreciate your help.

    Reply
  18. matt says

    10 August 2010 at 4:27 am

    @kirand: Can you post the URL of the form with the problem please, so we can take a look?

    Reply
  19. kirand says

    10 August 2010 at 9:12 am

    Thanks Matt.
    I could make the form work.
    Here’z my code:

    var focusElement= new Array();
    focusElement = Form.getElements(frm).findAll(function(elm){return $(elm).hasClassName(‘validation-failed’)})
    focusElement[0].focus();
    focusElement[0].select();
    return isValid = false;

    Reply
  20. heshan says

    10 August 2010 at 10:49 pm

    Hi all,

    This is something related with php as well as java script. If anyone can help me regarding this issue i would be very pleased.

    In a particular form, i have 2 fields namely customer id and Account type. Since there are many account types it is stored as a jump menu.

    There are seperate tables in my database to represent each of those accounts types. There is a seperate field in each table called account number which is auto incremented.

    If i select a particular account type in my form, i want to get the account number which is relevant to that account type. For an example if i click the submit button a message should appear like
    ” A new ……….( relevant account type) has been successfully opened”

    Any idea of how this could be done?

    Thanks,
    Heshan.

    Reply
  21. matt says

    12 August 2010 at 1:28 am

    @kirand: We’ll need to see the whole form I think! Can you post its URL?

    @heshan: See http://php.net/manual/en/function.mysql-insert-id.php

    Reply
  22. heshan says

    16 August 2010 at 2:32 am

    Thanks for your link,

    If we added data successfully to the database there is a message box displaying and saying ” Data has been added successfully to the database”.

    I want to know whether the icon of the message box can be changed?
    since it is a successful login……..

    Thanks,
    Heshan.

    Reply
  23. matt says

    18 August 2010 at 3:52 am

    @heshan: It depends how you’re creating the message box.

    If you’re using JavaScript alert(), then no. If you’re using something like http://jqueryui.com/demos/dialog/#modal-message then yes.

    Reply
  24. heshan says

    18 August 2010 at 10:32 am

    Then its ok. Thanks…….:-)

    Reply
  25. heshan says

    25 August 2010 at 2:05 pm

    Hi guys,

    I have a problem. Need a quick reply….I want something likes this to be done.

    When i want to logged out from the system or close an account etc i want to display this message. ” Are you sure you want to logged or something like” and “Yes and ” No” buttons are there.

    How this can be achieved??

    Thanks,

    Reply
  26. matt says

    25 August 2010 at 7:51 pm

    @heshan: Do you mean like a confirm dialog?

    var answer = confirm( "Are you sure?" );
    
    if ( answer == true ) {
      // yes
    } else {
      // no
    }
    

    [Edited by matt on 25-Aug-10 19:52]

    Reply
  27. heshan says

    26 August 2010 at 12:23 am

    yeah, i want a confirmation dialog box. It should be asking whether ” Are you sure you want to logged out from the system.”
    The user has the option to select ” Yes” and “No”…

    Reply
  28. matt says

    26 August 2010 at 8:32 pm

    @heshan: Yes the code I posted above will do that for you. However the buttons are usually called OK and Cancel, rather than Yes and No.

    Reply
  29. slotsbod says

    4 September 2010 at 11:57 am

    Hi

    I have a site that aloows a visitor to upload an image. BUT hackers are uploaoding PHP files because it has no validation.

    Can you tell me how I restrict the uploaded file to a giff or jpeg and disallow any other file type?

    Many thanks
    SlotsBod

    Reply
  30. matt says

    4 September 2010 at 10:23 pm

    @slotsbod: You can’t do this with JavaScript. You need to do it in your server-side code.

    Reply
  31. slotsbod says

    5 September 2010 at 7:01 am

    Hi Matt

    The code that I have on the upload page is below…

    I have tried using the Function TestFileType (fileName, fileTypes) code from your forum.

    …are you saying that the validation needs to be done in the PHP at the top of the page (where the code accepts the file and added it to my MYSQL database.)

    Many thanks

    = = = = = = = =

    <?php
    include("scripts/functions.php");
    $msg='';
    if ($_GET['getimage'] == '1')
    {
    	$uploadfile = "images/upload/" . $_FILES['txtFile']['name'];
      if (move_uploaded_file($_FILES['txtFile']['tmp_name'], $uploadfile))
      {
      	$msg = $_FILES['txtFile']['name'];
      }
      $fields[0] = 'path';
      $values[0] = makeString($msg);
      insertTable('image',$fields,$values);
    }
    ?>
    
    
    <html>
    <head>
    <title></title>
    
    <script language="Javascript">
    
    function TestFileType( fileName, fileTypes )
    {
    if (!fileName) return;
    
    dots = fileName.split(".");
    //get the part AFTER the LAST period.
    fileType = "." + dots[dots.length-1];
    
    return ('.'+fileTypes.join(".").indexOf(fileType) != -1) ?
    alert('That file is OK!') : 
    alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
    }
    
    function getimage()
    {
    	if (document.getElementById("txtFile").value == '')
    	{
    		alert("No Image Selected.");
    		return;
    	}
    	document.forms['Form1'].action = "getimage-new.php?getimage=1";
    	document.forms['Form1'].submit();
    }
    function body_onload()
    {
    	if ('<?echo($msg);?>' != '')
    	{
    		window.opener.imageUploaded('<?echo($msg);?>');
    		window.close();	
    	}
    }
    </script>
    
    </head>
    

    [Edited by slotsbod on 05-Sep-10 07:02]

    Reply
  32. matt says

    5 September 2010 at 10:03 pm

    @slotsbod:

    “are you saying that the validation needs to be done in the PHP at the top of the page”

    Yes. JavaScript validation is pointless for what you need, since it is trivial to circumvent. You need to validate on the server and reject the file if it’s not of the right type.

    Reply
  33. sania says

    2 December 2010 at 6:36 am

    heyy can u plzz solve dis ques

    create form for sudent registration which would contain following feilds
    1 first name
    2 last name
    3 fathers first name
    4 fathers last name
    5 class for registration
    6 stream
    7 bus student (checkbox)
    8 fees
    9 submit

    VALIDATIONS
    1 the first name of student and father should start with first letter
    it should not be blank
    first name and last name should not match
    2 if the class is 11 or 12 the stream field should become enable
    otherwise it should be disabled
    3 if the class of student is 1-5 the feees feild should be filled with rs2000
    6-10 rs 3000
    11-12 rs 4000
    4 if the student is bus student then fees = +1500

    Reply
  34. MaryBlight says

    19 January 2011 at 7:31 pm

    Hi Matt,

    Very clear explanation. Thanks so much.

    One thing I am wondering, is can the javascript code also be in the <body> of the html document? I need to put a form validation into a page where the hosted solution does not give you access to the <head> tags.

    Will the form still remember the answers even if not all questions are filled in, or will it clear on the validation error message, so that the user has to start the form again?

    Thanks so much for your help. I’m trying to understand submit and clear actions on form validation

    Reply
  35. laisunshine says

    21 January 2011 at 11:42 am

    Hello,
    I have a question. How can I get the alert box to only appear once with all of the errors on it? So it would be a multi-line error box? Thank you!

    Reply
  36. matt says

    23 January 2011 at 8:43 pm

    @MaryBlight: Yes, if you put it towards the start of the body element then you should be OK. The validation does not clear the form.

    @laisunshine: Rather than using alert()s for each field, just concatenate the error messages together into a string (separated by e.g. “\n”), then display the final string in an alert box.

    Reply
  37. asharani says

    25 January 2011 at 5:07 am

    Hi all,

    I need to create an alert box in a particular time for every week. Could anyone one please tell me how is it possible ?

    Reply
  38. matt says

    27 January 2011 at 10:28 pm

    @asharani: Please post your question in a new topic:

    http://www.elated.com/forums/authoring-and-programming/topic/new/

    Reply
  39. jjj84 says

    11 February 2011 at 5:33 pm

    Hello guys. I had the script working as intended for more than 1 field, but I am having trouble now. I’m not the best with Javascript, so if anyone could look it over and let me know the problem, I’d appreciate it.

    The address is:
    http://www.shipapallet.com/requestquote2.html

    As I was setting up the validation for each field, it looked like it was working as it should. When I had got down to the end, I’m thinking a character was misplaced or something, because now only the ‘approximate weight’ field is being validated. Any ideas?

    Reply
  40. matt says

    11 February 2011 at 9:13 pm

    Hi jjj84,

    It’s because you have lots of validate_form() functions in your code. You can’t have more than 1 function with the same name in a script.

    Instead, combine your checks into 1 validate_form() function, as shown in the tutorial:

    http://www.elated.com/res/File/articles/development/javascript/form-validation-with-javascript/complex_form_source.html

    Cheers,
    Matt

    Reply
  41. jjj84 says

    14 February 2011 at 10:43 am

    Matt,

    Thanks for the update! It works now as intended. Great script.

    J.

    Reply
  42. jjj84 says

    15 February 2011 at 2:28 pm

    Matt,
    Thanks for your help but I am now having another issue due to a requested change on the same form.

    All the validation appears to be working as it should except for on the dropdown list items. The dialog box pops up to indicate the user about the 1st dropdown they need to select, but then the form is being auto-submitted after that. The box that is popping up is for: Originating from a Residence or Business?

    The link is below:
    http://www.shipapallet.com/requestquote-test.html

    Any idea on what is causing this issue? LIke I mentioned, I am new to Javascript so it may be something I have overlooked. Any help is appreciated.

    Thanks again,
    Josh J.

    Reply
  43. matt says

    15 February 2011 at 7:09 pm

    @jjj84: Your problem is with this line:

    	if ( document.sapquote.loaddock-origin.selectedIndex == 0 )
    

    You can’t use hyphens like this – JavaScript thinks you want to subtract origin from loaddock. Change your field names to not use hyphens. Alternatively (and better), use id instead of name. You can then use hyphens in your ids.

    Same with loaddock-destination.

    Cheers,
    Matt

    Reply
  44. jjj84 says

    16 February 2011 at 10:04 am

    Ah ok! Got it now, works great. Thanks again!

    Reply
  45. catron says

    16 February 2011 at 1:44 pm

    I’m hoping you can provide me with some guidance. I have a registraion form setup with javascript validation in place, but there is one place I’m having trouble. I have a dropdown selection list, and based on the selection, there are text fields that are hidden or displayed for more info. So if you select the second item in the drop down, a text field associated with that selection appears. My issue is how to make that text field required, but only required based on drop down selection. I know there are ways to do this with radio buttons and checkboxes, but can it be done with dropdowns as well? The form is large so I didn’t want to paste all here, but the snap shot of the items I’m referring to are:

    
    <tr><td colspan=2 width="525" align="center">
    <a class="form">Please let us know how you learned about us.<br></a></td></tr>
    <tr>
    <td colspan=2  width="525" align="center" class="form">
    <select id="dropdown1" name="dropdown" onchange="display(this,'Google Search','Yahoo Search','Bing Search');" size="1" style="width:320px; font-size:11px; font-weight: bold; color: #686363;">
    <option>Please select:</option>
    <option value="Google Search">Google Search</option>
    <option value="Yahoo Search">Yahoo Search</option>
    <option value="Bing Search">Bing Search</option>
    <option value="Other">Other</option>
    </select>&nbsp;*
    </td>
    </tr>
    </thead>
    
    
    <tbody id="Google Search" style="display: none;">
    <tr>
    <td class="form" align="right"><br><br>Keywords used for search <font color="red">(Required)</font>:&nbsp;&nbsp;</td>
    <td class="field"><br>
    <input type="hidden" class="tbox1" id="textfield14" name="googlekey" size="40" value="-" />
    <input type="text" class="tbox1" id="textfield14" name="googlekey" size="40" value="" /></td>
    </tr>
    </tbody>
    
    
    <tbody id="Yahoo Search" style="display: none;">
    <tr>
    <td class="form" align="right"><br><br>Keywords used for search <font color="red">(Required)</font>:&nbsp;&nbsp;</td>
    <td class="field"><br>
    <input type="hidden" class="tbox1" id="textfield15" name="yahookey" size="40" value="-" />
    <input type="text" class="tbox1" id="textfield15" name="yahookey" size="40" value="" /></td>
    </tr>
    </tbody>
    

    Is it possible to make the the text field with name=googlekey required if some selects Google Search in drop down…but not required if they make some other selection? Thanks, David

    [Edited by catron on 16-Feb-11 13:51]

    Reply
  46. matt says

    20 February 2011 at 7:14 pm

    @jjj84: Great stuff. 🙂

    @catron: Yes, you could write something like:

        if ( document.contact_form.dropdown.selectedIndex == 1 && document.contact_form.googlekey.value == ""  )
        {
            alert ( "Please fill in the googlekey field" );
            valid = false;
        }
    
    Reply
  47. pakits says

    23 February 2011 at 8:44 am

    im having trouble with my student registration form..

    if you choose the subjects BSIT, BSMATH,BSED,BEED..the year level will be limited until 4 year only while if course is BSCE,BSGE,BSArch it will limit until 5 year.. how to validate it?? can anyone help me.. thanks in advance…

    <table cellpadding=”10″ cellspacing=”10″ style=”text-align:left;margin-left:15em” >
    <tr>
    <td>User Name</td>
    <td><input name=”uname” type=”text” id=”uname” onKeyUp=”isalphanum(this)” value=”” size=”16″/></td>
    </tr>

    <tr>
    <td>Password</td>
    <td><input type=”text” name=”password” value=”” size=”16″ onKeyUp=”isalphanum(this)” /></td>
    </tr>
    <tr>
    <td>Id No. </td>
    <td><input name=”idno” type=”text” id=”idno” onkeyup=”isnum(this)” value=”” size=”8″ /></td>
    </tr>
    <tr>
    <td>Name</td>
    <td><input name=”name” type=”text” id=”name” onkeyup=”isalpha(this)” value=”” size=”16″ /></td>
    </tr>
    <tr>
    <td>Course</td>
    <td>
    <select name=”course” id=”course” >
    <option>choose….</option>
    <option value=”BSIT”>BSIT</option>
    <option value=”BSMATH”>BSMATH</option>
    <option value=”BSED”>BSED</option>
    <option value=”BEED”>BEED</option>
    <option value=”BSPSYCH”>BSPSYCH</option>
    <option value=”BLIS”>BLIS</option>
    <option value=”BSCE”>BSCE</option>
    <option value=”BSGE”>BSGE</option>
    <option value=”BSArch”>BSArch</option>
    </select>
    </td>
    </tr>
    <tr>
    <td>Year</td>
    <td><input name=”year” type=”text” id=”year” onkeyup=”isnum(this)” value=”” size=”8″ /></td>
    </tr>
    </table>

    Reply
  48. matt says

    28 February 2011 at 4:24 am

    @pakits: Please post your question in a new topic:

    http://www.elated.com/forums/authoring-and-programming/topic/new/

    Reply
  49. jhollender says

    20 April 2011 at 10:05 am

    Hi, and thanks for all of the examples. I am writing a script that validates two select menus. Could you please give me an example of how to check them one at a time and how to concatonate the errors if they exist?

    Reply
  50. matt says

    25 April 2011 at 2:20 am

    @jhollender: “Validating drop-down lists” in the article shows how to check if a user has selected an option in a select menu.

    To concatenate the error messages, use “+”. For example:

    errorMessage += "Please select your Age.\n"
    
    Reply
  51. ElizaKaye says

    25 April 2011 at 11:15 pm

    Hi

    Thanks for your codes. I am trying to validate “surname” in a form.

    I need to check that it is not “empty” and if not they are alpha characters with -, space and ‘ special characters and with a limit of 30 chars.

    The name of my form is “myForm”

    I have not been able to find code anywhere that incorporates the 2 (That is, empty or alpha).

    The name of the function is validateForm()

    Reply
  52. matt says

    28 April 2011 at 6:54 am

    @ElizaKaye: Something like this should do what you need (I haven’t tested it mind!):

    if ( !document.contact_form.surname.value.match( /^[a-zA-Z- ']+$/ ) || document.contact_form.surname.value.length > 30 ) {
      alert ( "Please enter your surname." );
      valid = false;
    }
    

    You’ll need to put that inside your validate_form() function.

    Cheers,
    Matt

    Reply
  53. gauthamvit says

    6 July 2011 at 10:45 am

    Very useful. I recently stumbled across http://rindovincent.blogspot.com where i found a simple JavaScript validation form for beginners. I hope this will help some beginners.

    Reply
  54. peterfc2 says

    1 August 2011 at 2:51 am

    http://www.elated.com/res/File/articles/development/javascript/form-validation-with-javascript/complex_form.html

    Looking for a solution to trapping the space being entered.

    if ( document.contact_form.contact_name.value == "" )
        {
            alert ( "Please fill in the 'Your Name' box." );
            valid = false;
        } 
    []=space
    In your example if one enters [] [] [] it does not trap it.
    
    How would you stop just spaces being entered.
    Reply
  55. matt says

    8 August 2011 at 7:39 am

    @peterfc2: Try the ‘===’ operator instead of ‘==’.

    Reply
  56. eyefly says

    5 November 2011 at 10:44 am

    Hi
    Thanks for the information! I get my form to work with the validation, but everyone who first submits the form gets this error: “403 No variable substitutions in template”
    When you reload the page the form sends perfectly. ??? I cant figure that out. http://www.eyefly.co.za/form.html
    Please help!

    Reply
  57. matt says

    7 November 2011 at 12:37 am

    @eyefly: I’m guessing you’re using cgiemail to process your form on the server?

    http://web.mit.edu/wwwdev/cgiemail/

    This might help:

    http://www.lunarforums.com/c_perl_cgi_support/cgi_error_403_no_variable_substitutions_in_template-t26554.0.html

    Reply
  58. eyefly says

    7 November 2011 at 12:49 am

    Thanks for the reply – It is a cgi script: It was only after deleting my browser history that a correction in my template.txt works for me. All fine thanks for the good article.

    Reply
  59. Shone says

    2 December 2011 at 10:18 am

    Hi,

    If I have this code :

    function validation(){
    		
    		
    		valid = true;
    		
    		if (document.myForm.name.value ==""){
    		
    		alert("Please enter your name");
    		valid = false;
    		}
    		if (document.myForm.lastname.value ==""){
    		
    		alert("Please enter your lastname");
    		valid = false;
    		}
    		if (document.myForm.address.value ==""){
    		
    		alert("Please enter your address");
    		valid = false;
    		}
    		
    		return valid;
    

    How can I show all the form validation errors together in a message box ?

    Reply
  60. matt says

    6 December 2011 at 2:03 am

    @Shone: Rather than using alert()s for each field, just concatenate the error messages together into a string (separated by e.g. “\n”), then display the final string in an alert box if valid == false.

    Reply
  61. edwind says

    22 December 2011 at 4:44 am

    I have a problem with my form. It has three fields which I want to validate but in testing it the first incident of validation causes the alert to pop up but then when I click OK on the alert it submits the form anyway without letting me complete the field and continue to the other fields.
    It can be found at;
    http://www.46thpreston.org.uk/formvalidtest.htm

    Reply
  62. Kan says

    18 January 2012 at 8:46 pm

    Hi Matt,

    I find your site very helpful.
    I am an ms access guy and very new to javascript, I am trying an web application with php & mysql.

    Need help for js validation in my school project.

    Tablename : Table1
    Feilds : Name, Class, CheckboxBook1, CheckboxBook2

    Example Data:-

    Name: gary Class: 1A
    jane 1A
    sree 1B
    rita 1B
    jai 1B

    Validation : Each class can only select not more than 2 of Book1 and 2 of Book2

    Please give me the code .

    Thanking you.

    Reply
  63. tracie says

    8 March 2012 at 5:21 pm

    Thank you for the great code! Validation is working when I test the forms but I am getting emails with 1 or -1 in fields (instead of a valid phone or email, etc.) AND I am getting 20, 40, 80 at one time.

    I have tried to enter a 1 or -1 and it gives me the appropriate error message so I am not sure how I am getting these emails.

    Can you give me an idea where to look / what I should do to stop these form submissions since they have gotten around the validation.

    THANK YOU !!!

    Reply
  64. matt says

    9 March 2012 at 6:13 pm

    @tracie: Sounds like a problem with your form-to-email script running on your server, rather than a JavaScript problem.

    Reply
  65. khoder says

    21 April 2019 at 8:28 pm

    Visitor’s name (cannot be empty and can only consist of letters or spaces)

    Reply
    • Adarsh says

      30 January 2020 at 4:49 am

      //in pattern it’ll allow Capital and small letter and space as well
      // also it has minimum 2 character and maximum 10 character

      Reply
  66. Zouitine Firas says

    25 October 2019 at 10:19 am

    i’m confused why this code doesn’t run , i want to rum a form validation for my e-mail and my password “both type text”

     
    function formvalidation(){
    
    if (document.forms["formname"]["firstname"].value == ""){
        alert ("Please Enter Your First Name")
    }
    if (document.forms["formname"]["lastname"].value == ""){
        alert ("Please Enter Your last Name")
    }
    if (document.forms["formname"]["adress"].value == ""){
        alert ("Please Enter Your adress")
    }
    
    
    
    if (document.forms["formname"]["email"].value == ""){
        alert ("Please Enter Your email")
    }
    else if (/\S+@\S+\.\S+/.test(document.forms["formname"]["password"].value)){
                return true;
            }
            else
            {
                alert('Please provide a valid email address');
              return false;
          }
    
    
    if (document.forms["formname"]["password"].value == ""){
        alert ("Please Enter Your password")
    }
    else if (/^(?=.*\d)(?=.*[A-Z])[a-zA-Z0-9]{8,}$/.test(document.forms["formname"]["password"].value)){
        return true;
        }
        else
          {
            alert("Password Not Valid !!"); 
            return false;
        }
    
    
    if (document.forms["formname"]["comment"].value == ""){
        alert ("Please Enter Your comment")
    }
    
    
    else {
        alert ("You are successfully registered")
    }
    } 

    i don’t know if this synthax is good or not!!! can you help me please ^^

    Reply
    • Matt Doyle says

      1 November 2019 at 12:12 am

      Check your browser’s console. What error message(s) are you seeing?

      Reply
  67. Adarsh says

    30 January 2020 at 4:55 am

    if most of form validation is to be done with HTML5 attribute “Pattern” of element “Input” , then why we use comparatively long code of JavaScript instead of little bit code of html ?

    Reply
    • Matt Doyle says

      6 February 2020 at 2:55 am

      HTML5 was released in 2014. This article was written in 2001.

      Reply
  68. Chet says

    8 December 2020 at 8:48 pm

    Does this work if you don’t have the cgi file? The client-side still looks at the cgi file. Without it this won’t work correct? You do not offer to download the file, so how can you get this to work without it?

    Reply
  69. Sara Karlsen says

    19 March 2021 at 7:51 pm

    Hi,

    I am very new to Javacript and I am struggling here. After validation is OK, can I show a success message? I want to replace the innerHTML of the form when it has been validated.

    Best wishes,

    Sara

    Reply
    • Matt Doyle says

      22 March 2021 at 1:14 am

      Yep, it’s certainly doable. You’ll need to return false from the validator to prevent the browser sending the form. Then you can use something like innerText to display a message inside the form.

      Reply
      • Gopika says

        30 July 2021 at 2:47 pm

        Thanks for the blog, it was really helpful for me as a beginner.
        If you don’t mind I’m here for a help
        I need to know that instead of the alert message can I indicate the error with a background color change in the textbox.

        Reply
  70. Hasan Imam says

    6 August 2021 at 1:53 pm

    I want to validate just which line I select in form. But here when loop through the fields It check all the fields which was not selected by me in the form.
    var possible_total_line = document.getElementById(“possible_line_number”).value;

    for(var i=1;iend_line) {

    alert(“Start Line must be lesser than End line.”);
    document.getElementById(start_line).focus();
    return false;
    }
    else if((start_line == end_line)){

    alert(“Start Line must not be equal to End line.”);
    document.getElementById(start_line).focus();
    return false;
    }
    }

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits