The form data repeated backWhen forms are filled in mistakes are made.  Form validation is what you do to check that those mistakes don't end up in the database.  Currently products.html has a form on it - look at it to remind yourself.  Submit the form without filling in anything and you can see that most of the entries are blank as they have no default value (butter should show up as the default spread).  If this data was put in the database it would be useless so we will add JavaScript checks to see if the fields have been completed.

Make sure products.html has a src in the script element pointing to pandora.js.  Add an onsubmit event trigger (remember the return part) to the form element.  The function you are about to create will check for completeness so use a suitable name.  Test that the function is working by adding two lines temporarily: a simple alert and a return false.  Then try submitting the form to check that the function is triggered.  Comment out the alert and return.

Now you can add code to check each thing.

Filling and bread

These three are all required fields.  Without them the sandwich cannot be made.  If they are left blank that must be a mistake:

  1. get the value of each of these three form fields using getElementById and put each one into a variable
  2. use three alert lines to check that the value is being collected properly
  3. test it (if the fields are not set the alert messages should be blank, if selections have been made they should say which ones)
  4. comment out the alert lines
  5. under all of them create a single if statement which checks if any of the three is not changed from the default by using this condition: filling.length==1 || style.length==1 || bread.length==1 (the first entry in the drop downs always contains a single space so will be length 1 if the user has not made a change)
  6. pop up an alert if any of them are empty and return false
  7. add an else which returns true

When testing the form should submit properly only if all three are selected.

Spread, extras and comments

These do not need validation as the spread cannot be wrong and the other two are optional.


This is required and also needs to be a reasonable length.  No address is likely to be less than 5 characters long.  Therefore check for ones less than that more or less as you did for the filling etc..