Spelchan.com Logo

From Scratch Web Games: A Beginners Guide to Game Development using HTML, CSS, and JavaScript

Chapter 5.16: JavaScript Validation

Using JavaScript to perform additional validation on a form is very easy to do, you simply need to add an onsubmit event set in the form that either has your JavaScript code in it or calls a JavaScript function. This event gets called when the submit button is pressed and returns true if the form is valid or false if there are issues with the form. Below is the sample form that we will be using for this section:

<form name="testForm" action="FormSubmitPage.html"
onsubmit="return validateForm()" method="post">
<label>
Text: <input type="text" name="testText"><br />
</label>
<label>
Number: <input type="number" name="testNumber"><br />
</label>
<label>
Pick: <input type="radio" name="g1" value="a">Alpha
<input type="radio" name="g1" value="b">Beta
<input type="radio" name="g1" value="c">Gamma
<br/>
</label>
<label>
<input type="checkbox" name="cb">I am not a robot
<br />
</label>
<input type="submit" value="Submit">
</form>




Within the function that you created to handle the validation (validateForm in this case) you write code to check if the form is good. This can be combined with the built-in checks that HTML provides, which you can check using JavaScript by using the checkValidity() function on the element you want to verify. If everything in the form meets your requirements then you return true which will cause the submit action to be performed, or false which cancels the submit.

You need to provide error information yourself. Changing the style of invalid form items is the current trend. This can be done by using the id of the element that is at fault, but you will notice that our sample code seems to have not specified any ids for the elements. This was done on purpose to demonstrate another feature of JavaScript, or more precisely, the DOM model.

The document object has a forms variable that holds information about all the forms on the page. This is a multi-dimensional array with the first [] being the name of the form and the second [] being the name of the input item. We will be covering arrays, multi-dimensional arrays, and associative arrays in chapter 7 but for using them with forms it is fairly straightforward. You simply get the element putting the form you want in the first square bracket and the element in the second

let element = document.form[“formName”][“elementName”];

Typically, you would then grab the value or call a method. If you are just grabbing a value and not planning on using the element for other tasks, you can do the following:

let s = document.form[“formName”][“elementName”].value;

Testing text boxes generally involves making sure correct length, or some other checks such as making sure first letter is a letter and capitalized. As numbers can be returned as string, it is a good practice to use the Math.floor function to force them into an integer.

// Test text
let testText = document.forms["testForm"]["testText"].value;
if (testText.length < 3) {
alert("Name must be at least 3 characters");
return false;
}

// Test number range
let testNumber = Math.floor(document.forms["testForm"]["testNumber"].value);
if ((testNumber < 1) || (testNumber > 10)) {
alert("Number must be between 1 and 10");
return false;
}

Because radio buttons have a value that indicates which button is checked, the value is the name of the radio button that is checked for that group. An empty string is returned if no radio button is checked. Checkbox values are the name of the checkbox so to get if they are checked, use the checked attribute.

// Test radio button
let rad = document.forms["testForm"]["g1"].value;
if (rad == "") {
alert("Must select greek letter");
return false;
}
// Test checkbox
let cb = document.forms["testForm"]["cb"].value;
console.log("checkboxes always have name as value: "+cb);
cb = document.forms["testForm"]["cb"].checked;
if ( ! cb) {
alert("No robots allowed!");
return false;
}

And, as mentioned already, if there are no problems with the form you should return true.

At this point we have covered most things you would need to know about forms. Now would be a good time to try to put what you learned into practice as using the concepts you have been shown is how you enforce what you have learned. The next section is this chapter’s project.

Chapter contents

Chapter 5 Contents

5.1 Forms Cheat Sheets

This chapter's summary cheat sheet.

5.2 The client-server model

How forms are traditionally used.

5.3 The Form tag

How to set up a form in HTML.

5.4 Inputting text

Getting text input from the user.

5.5 Specialized text formats

Making your input fields more specific and semantic.

5.6 Form cosmetics

Making forms look more like printed forms.

5.7 checkboxes & radio buttons

How to use Checkboxes and Radio buttons.

5.8 Numbers and Dates

Using numbers and dates gives your user better GUI controls.

5.9 special purpose input types

The reset, button, image, color, and file input types.

5.10 Option Select

The select element lets users select options from a drop-down list.

5.11 Data Lists

The datalist elements lets you create pull-down lists for input elements.

5.12 Output

Displaying values in a form.

5.13 dialog box concepts

Built in dialog boxes and pre-dialog tag handmade dialogs.

5.14 using dialog boxes

The <dialog> tag and using it to create dialog boxes.

5.15 Validating forms

Review of validating forms in HTML.

5.16 JavaScript Validation

How to use JavaScript to prevent invalid forms from being submitted.

5.17 Project: Trivia

Chapter project: Trivia game

5.18 Trivia Project Solution

Solution for the Trivia gaame

← previous section
Validation
next section →
Trivia Project
Table of Contents