Unable to get validation working no obvious errors

Just trying to teach myself a bit of HTML+Javascript but have run into an error trying to use an external javascript to validate a HTML.

Currently the HTML looks something like this.

<!DOCTYPE html>
<html lang="en">

<head>
<Title>Book Event</Title>
    <meta charset="utf-8">
</head>

<body>


<h1>Book Event</h1>

<p></p>

<p> Click on the numbers next to the event to autofill the form!</p>

<script src="validation.js"></script>

<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
	
  <label for="datemin">Date of Event:</label>
  <input type="date" id="datemin" name="datemin" min="2020-02-01"><br><br>
  
  <label for="ename">Event name:</label><br>
  <input type="text" id="ename" name="ename"><br>
  
  <label for="Time">Time of Event:</label><br>
  <input type="text" id="Time" name="Time" value=" "><br><br>
  
 <fieldset>
          <legend>Selecting Location</legend>
          <p>
             <label>Select Location</label>
             <select id = "Location" name = "Location">
               <option value = "L1">Perth</option>
               <option value = "L2">Duidgee Park, Toodyay</option>
               <option value = "L3">Canning Highway</option>
             </select>
          </p>
       </fieldset>
	<p> </p>
  <fieldset>
          <legend>Selecting Price</legend>
          <p>
             <label>Select Price</label>
             <select id = "Price" name = "Price">
               <option value = "P1">$20</option>
               <option value = "P2">$30</option>
               <option value = "P3">$40</option>
			   <option value = "P4">$50</option>
			   <option value = "P5">$80</option>
             </select>
          </p>
       </fieldset>
  
  
  <label for="quantity">Quantity:</label>
  <input type="number" id="quantity" name="quantity" min="1" max="99"><br><br>
  
  
  <input type="submit" value="Submit">
</form> 

<p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p>

<p></p>

<table>
<thead>
  <tr>
    <th></th>
    <th>   Event   </th>
    <th>   Date   </th>
    <th>   Time   </th>
    <th>   Location   </th>
    <th>   Price   </th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>   <a href="#" onClick="autoFill1(); return true;" >1</a>   </td>
    <td>   Fatboy Slim  </td>
    <td>   FEB 2   </td>
    <td>   Sun, 7:00 pm - 10:00 pm   </td>
    <td>   Perth   </td>
    <td>   $40   </td>
  </tr>
  <tr>
    <td>   <a href="#" onClick="autoFill2(); return true;" >2</a>   </td>
    <td>   Bastille   </td>
    <td>   FEB 4   </td>
    <td>   Tue, 7:00 pm - 10:00 pm   </td>
    <td>   Perth   </td>
    <td>   $30   </td>
  </tr>
  <tr>
    <td>   <a href="#" onClick="autoFill3(); return true;" >3</a>  </td>
    <td>   A-HA   </td>
    <td>   FEB 19   </td>
    <td>   Wed, 7:00 pm - 10:00 pm   </td>
    <td>   Perth   </td>
    <td>   $50   </td>
  </tr>
  <tr>
  
    <td>   <a href="#" onClick="autoFill4(); return true;" >4</a>  </td>
    <td>   Michael Buble   </td>
    <td>   FEB 21   </td>
    <td>   Fri, 7:00 pm - 10:00 pm   </td>
    <td>   Perth   </td>
    <td>   $80   </td>

  </tr>
  <tr>
    <td>   <a href="#" onClick="autoFill5(); return true;" >5</a>  </td>
    <td>   SAFIA   </td>
    <td>   FEB 29   </td>
    <td>   Sat, 12:00 pm   </td>
    <td>   Perth   </td>
    <td>   $30   </td>
  </tr>
  <tr>
  <td>   <a href="#" onClick="autoFill6(); return true;" >6</a>  </td>
  <td>   Perth Festival 2020 - Highway to Hell   </td>
  <td>   MAR 1   </td>
  <td>   Sunday   </td>
  <td>   Canning Hwy   </td>
  <td>   $20   </td>
  </tr>
  <tr>
  <td>   <a href="#" onClick="autoFill7(); return true;" >7</a>  </td>
    <td>   Toodyay Music Fest   </td>
    <td>   MAR 28   </td>
    <td>   Sat, 10:00 am - 9:00 pm   </td>
    <td>   Duidgee Park, Toodyay   </td>
    <td>   $20   </td>
  </tr>
  <tr>
  <td>   <a href="#" onClick="autoFill8(); return true;" >8</a>  </td>
    <td>   City And Colour   </td>
    <td>   APR 17   </td>
    <td>   Fri, 7:00 pm - 10:00 pm   </td>
    <td>   Perth   </td>
    <td>   $50   </td>
  </tr>
  <tr>
  <td>   <a href="#" onClick="autoFill9(); return true;" >9</a>  </td>
    <td>   Backstreet Boys 2020   </td>
    <td>   MAY 30   </td>
    <td>   Sat, 8:00 pm - 11:00 pm   </td>
    <td>   Perth   </td>
    <td>   $80  </td>
  </tr>
</tbody>
</table>

<p> </p>

<script>
  function autoFill1() 
  {
    document.getElementById('Location').value = "L1";
    document.getElementById('ename').value = "Fatboy Slim";
	document.getElementById('datemin').value = "2020-02-02";
	document.getElementById('Time').value = "7:00 pm - 10:00pm"
	document.getElementById('Price').value = "P3"
   }  
  function autoFill2() 
  {
    document.getElementById('Location').value = "L1";
    document.getElementById('ename').value = "Bastille";
	document.getElementById('datemin').value = "2020-02-04";
	document.getElementById('Time').value = "7:00 pm - 10:00pm"
	document.getElementById('Price').value = "P2"
   }
   function autoFill3() 
  {
    document.getElementById('Location').value = "L1";
    document.getElementById('ename').value = "A-HA";
	document.getElementById('datemin').value = "2020-02-19";
	document.getElementById('Time').value = "7:00 pm - 10:00pm"
	document.getElementById('Price').value = "P4"
   }
  function autoFill4() 
  {
    document.getElementById('Location').value = "L1";
    document.getElementById('ename').value = "Michael Buble";
	document.getElementById('datemin').value = "2020-02-21";
	document.getElementById('Time').value = "7:00 pm - 10:00pm"
	document.getElementById('Price').value = "P5"
   }
  function autoFill5() 
  {
    document.getElementById('Location').value = "L1";
    document.getElementById('ename').value = "SAFIA";
	document.getElementById('datemin').value = "2020-02-29";
	document.getElementById('Time').value = "12:00PM"
	document.getElementById('Price').value = "P2"
   }
  function autoFill6() 
  {
    document.getElementById('Location').value = "L3";
    document.getElementById('ename').value = "Perth Festival 2020 - Highway to Hell";
	document.getElementById('datemin').value = "2020-03-01";
	document.getElementById('Time').value = "Null"
	document.getElementById('Price').value = "P1"
   }
  function autoFill7() 
  {
    document.getElementById('Location').value = "L2";
    document.getElementById('ename').value = "Toodyay Music Fest";
	document.getElementById('datemin').value = "2020-03-28";
	document.getElementById('Time').value = "10:00am - 09:00pm"
	document.getElementById('Price').value = "P1"
   } 
  function autoFill8() 
  {
    document.getElementById('Location').value = "L1";
    document.getElementById('ename').value = "City and Colour";
	document.getElementById('datemin').value = "2020-04-17";
	document.getElementById('Time').value = "07:00pm - 10:00pm"
	document.getElementById('Price').value = "P4"
   } 
  function autoFill9() 
  {
    document.getElementById('Location').value = "L1";
    document.getElementById('ename').value = "Backstreet Boys 2020";
	document.getElementById('datemin').value = "2020-05-20";
	document.getElementById('Time').value = "08:00pm - 11:00pm"
	document.getElementById('Price').value = "P5"
   }    
</script>



</body>

</html>

With the validation.js looking like this,

function validateForm() 
	{
	var Location = document.forms["myForm"]["Location"].value;
	var eName = document.forms["myform"]["eName"].value;
	var	datemin = document.forms["myform"]["datemin"].value;
	var Time = document.forms["myform"]["Time"].value;
	var Price = document.forms["myform"]["Price"].value;
	var quantity = document.forms["myform"]["quantity"].value;
	
	if(Location == "") 
	{
		alert ("Please select a location.");
		return false;
		
	}
	if(ename == "") 
	{
		alert ("Please input an Event Name.");
		return false;
		
	}
	if(datemin == "") 
	{
		alert ("Please input the date of the event.");
		return false;
		
	}
	if(Time == "") 
	{
		alert ("Please input a Time for the event");
		return false;
		
	}
	if(Price == "") 
	{
		alert ("Please input a price.");
		return false;
		
	}
	if(quantity == "") 
	{
		alert ("Please input the amount of tickets you wish to purchase.");
		return false;
		
	}
	else
	{
		return true;		
	}
	}

Am I missing something, or doing something incorrectly? Thanks for any help!

The validate script would need to call a preventDefault() to stop the browser from taking it’s normal course of action.

That a side, you don’t really need this validate script, you can use ‘required’ in your HTML

<form class='events-form' name='events' action='#' method='post'>

  <label for="datemin">Date of Event:</label>
  <input type="date" id="datemin" name="datemin" min="2020-02-01" required>

  <label for="ename">Event name:</label>
  <input type="text" id="ename" name="ename" required>

  <label for="Time">Time of Event:</label>
  <input type="text" id="Time" name="Time" value=" " required>

  <fieldset>
    <legend>Selecting Location</legend>
    <label>Select Location</label>
    <select id = "Location" required>
      <option value="">Please choose a location</option>
      <option value = "L1">Perth</option>
      <option value = "L2">Duidgee Park, Toodyay</option>
      <option value = "L3">Canning Highway</option>
    </select>
  </fieldset>

  <fieldset>
    <legend>Selecting Price</legend>
    <label>Select Price</label>
    <select id = "Price" required>
      <option value="">Please choose a Price</option>
      <option value = "P1">$20</option>
      <option value = "P2">$30</option>
      <option value = "P3">$40</option>
      <option value = "P4">$50</option>
      <option value = "P5">$80</option>
    </select>
  </fieldset>

  <label for="quantity">Quantity:</label>
  <input type="number" id="quantity" name="quantity" min="1" max="99" required>
  <input type="submit" value="Submit">
</form>
1 Like

Hi @t3ngster, you don’t need any of that JS if you just add required attributes to those input elements. :-)

1 Like

The validate script would need to call a preventDefault() to stop the browser from taking it’s normal course of action.

Thanks so much for that, however I can’t seem to get it working, could you possibly give a small example of what this would look like in the given javascript?

That a side, you don’t really need this validate script, you can use ‘required’ in your HTML`

Gave this a go, and it works like a charm, I wanted to use the validate script to get an error message to appear in a message box, and also try out a bit of the validation in terms of javascript itself.

Hi @t3ngster, you don’t need any of that JS if you just add required attributes to those input elements. :-)

Thanks for your input! Yes required works, and the link was very insightful.

Like already stated all you need is required in the HTML. I did a validation script for my registration on my registration page form. It wasn’t really for validation, but to show real time response back on the status of their typing. All the true validation is done with required and on the server-side on the registration page.

Here’s the javascript for the registration page:

'use strict';

const d = document;

const unavailable = d.querySelector('.unavailable');
const recommendation = d.querySelector('.recommendation');
var username = d.querySelector('#username');
var password = d.querySelector('#password');
var data = {};

/* Success function utilizing FETCH */
const duplicateUISuccess = function (status) {
    /*
     * Make <span> HTML tag visible to highlight message
     * in red.
     */
    if (status) {
        unavailable.style.display = "inline-block";
    } else {
        unavailable.style.display = "none";
    }
};

/* If Database Table fails to update data in mysql table */
const duplicateUIError = function (error) {
    console.log("Database Table did not load", error);
};


const passwordUISuccess = function(status) {
    if (status === "Strong") {
        recommendation.style.cssText = "color: green; font-size: 1.0em; font-weight: bold;";
    } else {
        recommendation.style.cssText = "color: red; font-size: 0.8em; font-weight: normal;";
    }
    recommendation.textContent = status;
};

const passwordUIError = (error) => {
  console.log("Database Table did not load", error);  
};


/*
 * Grab the status if there is an error.
 */
const handleSaveErrors = function (response) {
    if (!response.ok) {
        throw (response.status + ' : ' + response.statusText);
    }
    return response.json();
};

/*
 *  Fetch ($.get in jQuery) that basic is a simplified newer Ajax
 *  protocol (function?). 
 */
const checkRequest = (sendUrl, succeed, fail) => {
    fetch(sendUrl, {
        method: 'POST', // or 'PUT'
        body: JSON.stringify(data)

    })
            .then((response) => handleSaveErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
};

/*
 *  Grab the keystrokes
 */
const checkForDuplicate = (e) => {
    e.preventDefault();
    const sendUrl = 'checkName.php'; // Name of php file:
    data.username = username.value; // Put the keystrokes in object var:    
    
    /* 
     *  Call the checkRequest Function using sendUrl variable as the name
     *  of the php file that will be used to check against the database table.
     */ 
    
    checkRequest(sendUrl, duplicateUISuccess, duplicateUIError); 
};

/*
 * Add an Event Listener to check for username already in 
 * database table. When the person types every keyup stroke
 * is checked against the database table. 
 */

username.addEventListener('keyup', checkForDuplicate, false);

const strongPassword = (e) => {
    e.preventDefault();
    const sendUrl = 'strongPassword.php';
    data.password = password.value;
    checkRequest(sendUrl, passwordUISuccess, passwordUIError);
};

password.addEventListener('keyup', strongPassword, false);

and the HTML Form:

        <div id="registrationPage">
            <form class="registerForm" action="" method="post" autocomplete="on">

                <h1><?php echo (isset($message)) ? $message : 'Register'; ?></h1>
                <p><?php echo (isset($errPassword)) ? $errPassword : "Please fill in this form to create an account."; ?></p>
                <hr>

                <label for="username"><b>Username <span class="unavailable"> - Not Available, please choose a different one.</span></b></label>
                <input id="username" type="text" placeholder="<?php echo (isset($statusUsername) && $statusUsername) ? "Username is not available, please re-enter!" : "Enter Username"; ?>" name="data[username]" value="<?php echo (isset($data['username'])) ? $data['username'] : null; ?>" autofocus required>

                <label for="email"><?php echo (isset($errEmail)) ? $errEmail : "<b>Email</b>"; ?></label>
                <input type="email" placeholder="Enter Email" name="data[email]" value="<?php echo (isset($data['email'])) ? $data['email'] : null; ?>" required>

                <label for="psw"><b>Password <span class="recommendation">recommendation at least (8 characters long, 1 uppercasse letter, 1 number, and 1 special character)</span></b></label>
                <input id="password" type="password" placeholder="Enter Password" name="data[password]" required>

                <label for="psw-repeat"><b>Repeat Password</b></label>
                <input type="password" placeholder="Repeat Password" name="data[repeatPassword]" required>
                <hr>

                <p>By creating an account you agree to our <a href="termsPolicy.php">Terms & Privacy</a>.</p>
                <input type="submit" name="submit" value="enter" class="registerbtn">


                <div class="signin">
                    <p>Already have an account? <a href="index.php">Sign in</a>.</p>
                </div>
            </form>
        </div>

There’s some PHP going on also with the script, but I just want to show the javascript. The e.preventDefault() isn’t probably needed as I’m just checking the input fields, but it doesn’t hurt. The registration form won’t go through anyways if the user just clicks on the submit button.

1 Like

There are better ways, but I think it’s good to experiment

You have an issue with inconsistent naming. It’s best to avoid using capital letters, unless in the form of camelCase. Either way you need to be consistent.

So first off some amends to your form. I have added a class name to the form, and amended the names to lowercase etc.

I have also removed the inline javascript onsubmit="return validateForm()", a very dated and somewhat messy practice.

<form class='events-form' name='eventsForm' action='#' method='post'>

  <label for="datemin">Date of Event:</label>
  <input type="date" id="datemin" name="datemin" min="2020-02-01" >

  <label for="ename">Event name:</label>
  <input type="text" id="ename" name="ename" >

  <label for="time">Time of Event:</label>
  <input type="text" id="time" name="time">

  <fieldset>
    <legend>Selecting Location</legend>
    <label>Select Location</label>
    <select id = "location" >
      <option value="">Please choose a location</option>
      <option value = "l1">Perth</option>
      <option value = "l2">Duidgee Park, Toodyay</option>
      <option value = "l3">Canning Highway</option>
    </select>
  </fieldset>

  <fieldset>
    <legend>Selecting Price</legend>
    <label>Select Price</label>
    <select id = "price" >
      <option value="">Please choose a Price</option>
      <option value = "p1">$20</option>
      <option value = "p2">$30</option>
      <option value = "p3">$40</option>
      <option value = "p4">$50</option>
      <option value = "p5">$80</option>
    </select>
  </fieldset>

  <label for="quantity">Quantity:</label>
  <input type="number" id="quantity" name="quantity" min="1" max="99" >
  <input type="submit" value="Submit">
</form>

Your <script src='validate.js'></script> needs to be moved to the bottom of the page before the end body tags. Otherwise it is looking for elements that have yet to be rendered in the page.

This is an amended validate js based on your script. I have added an eventListener to the form to listen out for the submit button. On clicking that it will run the validate function.

const form = document.querySelector('.events-form')

function validateForm(event) {

  event.preventDefault();

  const location = document.eventsForm["location"].value;
  const ename = document.eventsForm["ename"].value;
  const	datemin = document.eventsForm["datemin"].value;
  const time = document.eventsForm["time"].value;
  const price = document.eventsForm["price"].value;
  const quantity = document.eventsForm["quantity"].value;

  if (datemin === "") {
    alert ("Please input the date of the event.");
    return false;
  }

  if (ename === "") {
    alert ("Please input an Event Name.");
    return false;
  }

  if (time === "") {
    alert ("Please input a Time for the event");
    return false;
  }

  if (location === "") {
    alert ("Please select a location.");
    return false;
  }

  if (price === "") {
    alert ("Please input a price.");
    return false;
  }

  if (quantity === "") {
    alert ("Please input the amount of tickets you wish to purchase.");
    return false;
  }

  document.eventsForm.submit();
}

form.addEventListener('submit', validateForm, false)

Just to point out this is purely for your experimenting, as mentioned there are better way to do this.

As an aside, you can clean up your HTML. No need for empty paragraphs and break-returns to space out your elements — it just adds clutter. Instead you can use CSS

A very simple example, which I put in my head whilst testing

<style>
    label,
    input {
      display: block;
    }

    fieldset,
    input {
      margin-bottom: 1rem;
    }

    .events-form {
      max-width: 700px;
    }

    .upcoming-events th {
      text-align: left;
    }
</style>
2 Likes

@rpg_digital Thank you so much!

I tried everything you recommended but I think this was the main issue! I haven’t looked into CSS yet, but yeah I definitely see your point on cleaning up the HTML code. I just started learning HTML from trying my hand at C# and putting all the spaces just made it seem… more comfortable. Didn’t realise it was making odd looking gaps in the HTML. Yes, I will also endeavor to use a more uniform naming sense.

@Pepster64 Thanks a lot for your example, along with the notes in them, im still a beginner at Javascript and HTML so your script was full of unknowns, but i’m sure it will be very useful to me down the line as a good example for future activities.

Thank to everyone for all the help, I’ve learnt tremendously from your guidance.

1 Like