Copyright Derek O'Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.
HTML forms are used to get user input data from a webpage.
Input tags allow a user to input data into a form. There are various means of getting an input. The type attribute is used to identify the type of input that a given input tag accepts. The text input type includes:
Input of type text presents the user with a textbox.
<input type = "text">
You can type inside the "text" input box here:
Each input tag should have a name associated with it. The name attribute is associated with the data that the user inputs into the input tag when the data is sent to another webpage. We shall see how this works further down in these notes. Within a given form, each input tag should have a unique name.
<input type = "text" name = "someName">
Example of the text input types (Run Example)
<!doctype html>
<html>
<head>
<title>Course notes example code</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="Content-Language" content="en" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form>
<input type = "text" name = "someName">
</form>
</body>
</html>
Input of type password keeps the user's keystrokes hidden.
<input type = "password">
You can type inside the "password" input box here:
Password example (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <input type = "password" name = "passwordField"> </form> </body> </html>
The textarea tag is used to create a text area. The attribute rows and cols are used to specify the textarea's size. In the example below, the textarea will be five rows high. Normally, we should the textarea width and height in CSS.
<textarea rows = "5"></textarea>
You can type inside the textarea here:
Example of a textarea that is 5 rows high (Run Example)
<!doctype html>
<html>
<head>
<title>Course notes example code</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="Content-Language" content="en" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form>
<textarea rows = "5"></textarea>
</form>
</body>
</html>
An image can be used as a background for any element. Write code to use an image as a form background, as shown here.
The label tag defines a label for an <input> element. A label can be tied to an input by using the "for" attribute. The "for" attribute of the <label> tag must be equal to the id attribute of the related element to bind them together. Clicking on a label that is tied to an input causes the input to be selected, as shown in the example below. Normally, we can give the id attribute the same value as the name attribute (checkboxes and radio buttons are an exception to this rule) :
Example of a form label (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form>
<label for = "name1">Name 1: </label>
<input type = "text" id = "name1" name = "name1"><br>
<label for = "name2">Name 2: </label>
<input type = "text" id = "name2" name = "name2"><br>
<label for = "name3">Name 3: </label>
<input type = "text" id = "name3" name = "name3">
</form> </body> </html>
The placeholder attribute is used to provide an input hint to the user. It is displayed inside an input field as long as the field is empty. As soon as you start typing, the placeholder will disappear.
<input type = "text" placeholder = "Enter your username">
The value attribute is used to pre-assign values to input and textarea tags. The pre-assigned value is an actual value that will not automatically disappear when you start typing.
<input type = "text" value = "Some pre-assigned text">
A button is a clickable button that can drive some JavaScript code.
A reset button clears all elements in a form.
A submit button causes a form to be processed.
Buttons, reset buttons and submit buttons do not need to have a name attribute associated with them, as they are not ways of inputting data in a form. Instead, they are actions for driving the form.
The value attribute is used to place text onto to a button, reset button or submit button.
Example of a form that uses a button, reset button and submit button, along with values for the various buttons (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <label>Here is a button</label> <input type = "button" value = "Example Button"> <br> <label>Here is a reset button</label> <input type = "reset"> <br> <label>Here is a submit button</label> <input type = "submit"> </form> </body> </html>
Write code to create a form that allows a user to input a name and address. The user should be able to reset or submit the form, as shown here.
The select tag is used to contain either a drop-down menu or a list. If the size attribute is not set or if it is set to size = "1" then a drop-down menu is displayed. Setting the size to any value greater than 1 displays a list. By default, the size is set to 1, so the default display is a drop-down menu.
Each item in the drop-down menu or list is contained within an option tag. The option tag contains a value attribute. This specifies the value that will be sent if that option is selected when the form is submitted.
Example of a select drop-down menu and a list (Run Example)
<!doctype html>
<html>
<head>
<title>Course notes example code</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="Content-Language" content="en" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form>
<p>The list below is a drop-down menu because it does not have a size set. The drop-down menu has item 3 set to be initially selected.</p>
<select name = "menu">
<option value = "one">menu item 1</option>
<option value = "two">menu item 2</option>
<option value = "three" selected>menuItem3</option>
</select>
<p>The list below has a height of 5</p>
<select name = "list" size = "5">
<option value = "10">item 1</option>
<option value = "20">item 2</option>
<option value = "30">item 3</option>
<option value = "40">item 4</option>
<option value = "50">item 5</option>
<option value = "60">item 6</option>
<option value = "70">item 7</option>
<option value = "80">item 8</option>
<option value = "90">item 9</option>
<option value = "100">item 10</option>
</select>
</form>
</body>
</html>
Setting the attribute multiple will allow for multiple items in a list to be selected. Multiple selection is made using the mouse while holding down the control key or the shift key.
<select name = "menu" multiple>
Write code to allow a user to select multiple fruit items from a list box, as shown here.
The checkbox input allows a user to check items from a list of items. By default, check boxes initially appear without a check mark. Use the checked attribute to display a check mark. If a group of checkboxes are related then we should use the same name for all of them. In the example below, the three checkboxes are all colours.
Example of a checkbox (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <p>The last two checkboxes are pre-checked below.</p> <input type = "checkbox" name = "colour" value = "red"> <input type = "checkbox" name = "colour" value = "green" checked> <input type = "checkbox" name = "colour" value = "blue" checked> <br> <input type = "submit"> </form> </body> </html>
Write code to allow a user to check colour combinations and submit their selection, as shown here.
The radio button input type allows a user to select exactly one from a selection of items. Items that have the same name attribute are grouped together, as shown in the example below. The checked attribute is used to select an item when the webpage loads:
Example of a radio button (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <p>Below is a group of radio buttons. Item one has been set to be initially selected (i.e. checked).</p> <input type = "radio" name = "radiobuttonGroup1" value = "1" checked> <!-- The checked attribute is used to set the default selected item --> <input type = "radio" name = "radiobuttonGroup1" value = "2"> <p>Below is a second group of radio buttons. No item has been set to be initially selected.</p> <input type = "radio" name = "radiobuttonGroup2" value = "one"> <input type = "radio" name = "radiobuttonGroup2" value = "two"> <input type = "radio" name = "radiobuttonGroup2" value = "three"> <br> <input type = "submit"> </form> </body> </html>
What happens if more than one item in a radio button group is checked?
Write code to allow a user to select a model and colour of a car and to submit this data, as shown here.
Fieldset tags are used to group related form data together. A fieldset will draw a box around the items that it contains.
Example of a fieldset tag (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <fieldset> <label for = "name">Name:</label><input type = "text" id = "name" name = "name"><br> <label for = "address">Address:</label><input type = "text" id = "address" name = "address" autocomplete = "off"><br> <label for = "phone">Phone:</label><input type = "tel" id = "phone" name = "phone"> </fieldset> <br> <input type = "submit"> </form> </body> </html>
Write code to allow a user to enter their profile into a form, as shown here.
Extend the BMW car example, so that it uses fieldsets to seperate the model and car colour, as shown here.
A legend tag is used to place a heading on a fieldset, as shown in the example below.
Example of a legend (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <fieldset> <legend>Personal Details</legend> <label for = "name">Name:</label><input type = "text" id = "name" name = "name"><br> <label for = "address">Address:</label><input type = "text" id = "address" name = "address" autocomplete = "off"><br> <label for = "phone">Phone:</label><input type = "tel" id = "phone" name = "phone"> </fieldset> <br> <input type = "submit"> </form> </body> </html>
A fieldset can contain other fieldsets. Extend the personal profile code above so that is has a container fieldset, as shown here.
Extend the BMW example so that it uses legends instead of h2 tags, as shown here.
The file input type allows a user to select a filename.
Note that, although the filename is selected and can be submitted to another webpage, the actual file content is not uploaded. To do this requires server-side code, such as php.
Example of a File selection input (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <input type = "file" name = "file"> </form> </body> </html>
Using the accept attribute restricts the files that can be selected for uploading. In the example below, only image files will be displayed for selection.
Example using a file accept attribute (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <label>Select an image file:</label><input type = "file" name = "imageFile" accept = ".jpg, .gif, .png"> </form> </body> </html>
The input type hidden is used to hold data that is not displayed on the screen. Hidden input is used to hold data when programming in JavaScript. The data that is contained in a hidden input is sent to a new webpage along with the other input data when a form is submitted.
When you submit the form below you will see that the hidden value has been sent as part of the url.
Example of a hidden input (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <input type = "hidden" name = "hiddenName" value = "123"> <input type = "submit" > </form> </body> </html>
The action attribute identifies the action that is to happen to a form when it is submitted by a user. When a form is submitted, it will either be sent to another webpage to be processed or it will be emailed to some address.
To send the form data to another webpage, use the action below:
<form action = "http://www.somewebpage.com">
To email a form, use the action below. Note that email addresses need to have the suffix mailto:
<form action = "mailto:admin@mycompany.com">
The method atrribute defines how a form's data should be sent when a user submits the form to another webpage. Data can be sent using either a "get" or a "post" method.
Data sent using the "get" method is appended to the webpage url that appears in the browser window.
Using the get method a user can see a form's values in a url. This:
However:
The "post" method hides the form data when it is being sent to another webpage. Therefore, we can use post to send password details to another webpage. As post data is hidden, post cannot be used for either book-marking or as a debugging aid.
There is no limit to the size of a post, so post should be used to send large amounts of data to another webpage.
The filename assigned to the action attribute must exist. For the example below to work, the file "form_demo.html" must exist.
Example form using a get method (Run Example)
<!doctype html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form action = "form_demo.html" method = "get" target = "_blank"> <label for = "name">Name: </label><input type = "text" id = "name" name = "name"><br> <label for = "password">Password: </label><input type = "password" id = "password" name = "password"><br> <input type = "submit"> </form> </body> </html>
Change the method in the code above to "post" and see that the submitted url does not contain any form data, as shown here.
Write code to produce a form that asks a user to enter their name, address and phone number and lets the user submit this data, as shown here.
Write JavaScript code to extract and display the name, address and phone number from the submitted form in the question above, as shown here.
The autofocus attribute forces the input to focus on the element that has autofocus set.
Example of a form with autofocus set (Run Example)
<!DOCTYPE html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <label for = "name">name:</label><input id = "name" name = "name" autofocus><br> <label for = "address">address:</label><input id = "address" name = "address"><br> <label for = "age">age:</label><input id = "age" name = "age"><br> <input type = "submit"> </form> </body> </html>
Write code to place the autofocus on the age input instead of the name input.
Write code to see what happens when you place an autofocus on more than one input?
Setting the input type to be email will only allow valid email addresses to be submitted.
On the virtual keypad of a mobile device, the keyboard will change to be appropriate for inputting emails. For example, the "@" key will be made available.
<input type = "email">
Write code to see what happens if you try to submit a form that contains a non-valid email field, as shown here.
The "email" type performs automatic form validation. It will not allow a form to be submitted if the email is not valid.
The types listed below also support automatic form validation:
Setting the form attribute novalidate will turn automatic validation off.
Example of a form that has the novalidate attribute set (Run Example).
<!DOCTYPE HTML> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form novalidate> <input type = "email" name = "email"> <br> <input type = "submit"> </form> </body> </html>
Setting the input type to be url does not have any affect on users who are using a full size, laptop or PC, keyboard. However, virtual keypads on mobile devices will change the keyboard to be appropriate for inputting emails. For example, a ".com" key will be made available.
<input type = "url">
Setting the input type to be search will provide a cancel icon within the input field. This allows users to easily change their search input.
<input type = "search">
Write code to make a search form. A user should be able to enter a search term and submit it to google, as shown here.
Setting the type to be number ensures that only a number can be entered into the field. The field will show spinbox icons so that the user can iterate up and down through the number range.
<input type = "number">
The minimun and maximum range can also be set, as shown below:
<input type = "number" min = "20" max = "100">
A step size and a default start value, as shown below.
<input type = "number" min = "20" max = "100" step = "10" value = "40">
Setting the type to be range will set a number range to appear as a slider.
<input type = "range" min = "20" max = "100" step = "10" value = "40">
Write javascript code to display the current value of the slider, as shown here.
Setting the type to be date will let the user select from a calander.
<input type = "date">
Click on the field below to see the "date" type working.
The type can also be set to "time", "month" or "week".
<input type = "time"> <input type = "month"> <input type = "week">
Click on the field below to see the "time" type working.
Click on the field below to see the "month" type working.
Click on the field below to see the "week" type working.
Setting the type to be tel informs the browser that the user should be inputting a telephone number.
If a browser does not support tel, then it will treat the input as being a "text" input.
<input type = "tel">
Write code to allow a user to submit a telephone number, as shown here.
Regular expressions allow us to validate HTML input, so that only certain patterns of characters are accepted. The "pattern" attribute specifies a regular expression that an element's value is checked against when a form is submitted. It uses the exact same syntax as JavaScript regular expression do. The "pattern" attribute can be used on the elements listed below:
In HTML, regular expressions take the form below
pattern = "patternString"
A pattern is made up of one or more sub-patterns.
Each sub-pattern is of the form
([]{})
Where:
Various patterns of characters can be matched within a pattern:
Click here to see the full set of regular expressions.
Click here for a detailed lesson on regular expressions.
In the example below, the user must input a seven digit number (Run Example).
<!DOCTYPE html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <p>Enter a seven-digit number</p> <input type = "text" pattern="^[0-9]{7}$"> <input type = "submit"> </form> </body> </html>
In the example below, the user must input a decimal number (Run Example).
<!DOCTYPE html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <p>Enter a decimal number, such as 0.0, 1.0, 34.987</p> <input type = "text" pattern = "^[0-9]+\.[0-9]+$"> <input type = "submit"> </form> </body> </html>
In the example below, the user must input a ten-digit mobile telephone number that begins with 08x (Run Example).
<!DOCTYPE html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <p>Enter a ten-digit number that begins with 08x7</p> <input type = "text" pattern="^08[1-9][0-9]{7}$"> <input type = "submit"> </form> </body> </html>
When using regular expressions, it is important to inform the user of the expected format. The default error message that is given for an incorrect regular expression is the generic string “Please match the requested format.”. If it exists, then the value in the title attribute of an input tag will appear after the generic message.
In the example below, the user is informed that a valid mobile telephone number is required (Run Example).
<!DOCTYPE html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <p>Enter a ten-digit number that begins with 08x</p> <input type = "text" pattern="^08[3567][0-9]{7}$" title = "Enter a ten-digit number that begins with 08x"> <input type = "submit"> </form> </body> </html>
In the example below, the user must input a valid date (dd-mm-yyyy). (Run Example)
<!DOCTYPE html> <html> <head> <title>Course notes example code</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <p>Enter a date in the format dd-mm-yyyy</p> <input type = "text" pattern="^(0[1-9]|[12][0-9]|3[01])[\-\/\. ](0[1-9]|1[012])[\-\/\. ](19|20)\d\d$" title = "Enter a date in the format dd-mm-yyyy"> <input type = "submit"> </form> </body> </html>
In the exercises below, when making a pattern, it can be useful to use a tool, such as https://regex101.com/ to check that the pattern is valid.
Write code to accept a date in the American format mm-dd-yyyy, as shown here.
Write code to accept a date in the format dd-mmm-yyyy, using lowercase jan, feb, mar... as the month, as shown here.
Adjust the example above, so that the months can be any combination of lowercase and uppercase letters, such as JAN, Feb, mar, ApR, as shown here.
In the pattern below, the user must input at least one one digit and one lowercase letter (Run Example)
<!DOCTYPE html>
<html>
<head>
<title>Course notes example code</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="Content-Language" content="en" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form>
<p>Enter at least one digit and one lowercase letter</p>
<input type = "text" pattern="^(?=.*[0-9])(?=.*[a-z]).+$" title = "Enter at least one digit and one lowercase letter">
<input type = "submit">
</form>
</body>
</html>
Adjust the code above, so that the user has enter at least one digit and one letter (either uppercase or lowercase), as shown here.
Write code to force the user to input a password that must contain an uppercase letter, a lowercase letter, a digit and one of these characters (£!#€$%^&*). In addition, the password should be at least ten digits long, as shown here.
In the pattern below, the user must input a valid email (Run Example)
<!DOCTYPE html>
<html>
<head>
<title>Course notes example code</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="Content-Language" content="en" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form>
<p>Enter an email address</p>
<input type = "email" pattern = "^[^@]+@[^@]+\.[a-zA-Z]{2,6}$" title = "Enter an email address">
<input type = "submit">
</form>
</body>
</html>
Write code to only allow valid lowercase DkIT emails (i.e. end with "@dkit.ie" or "@student.dkit.ie") to be submitted, as shown here.
Adjust the code above, so that the user can enter their DkIT email in upper and lower case letters, as shown here.
Go online and find a regular expression to validate international telephone numbers using the EPP format, as shown here.
Go online and find a regular expression to validate credit card numbers, as shown here.
Setting the type to be color will let the user select a colour from a colour picker.
<input type = "color">
Click on the colour selector below to see it working.
Write javascript code to allow the user to change the background colour of a webpage, as shown here.
Setting the "required" attribute for a field will force the user to enter a value for the field before they can submit a form.
<input type = "email" required>
Write code that forces a user to enter a name and an email before the allowing the user to submit a form, as shown here.
The autocomplete attribute specifies whether a form or input field should have autocomplete on or off. When autocomplete is turned on, the browser automatically completes values, based on values that the user has entered before. It is possible to have autocomplete 'on' for the form, and 'off' for specific input fields, or vice versa.
The autocomplete attribute works with <form> and the following <input> types:
Autocomplete is not support on Chrome browsers.
In the code below, autocomplete has been enable for all fields in the form, except the address field.
Example using autocomplete (Run example)
<!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Course notes example code</title> </head> <body> <form autocomplete = "on"> <label>Name:</label> <input type = "text" id = "name"> <br> <label>Address:</label> <input type = "text" id = "address" autocomplete = "off"> <br> <label>Phone:</label> <input type = "tel" id = "phone"> <br> <input type = "submit" value = "Submit"> </form> <p>Input a name, address and phone number.<br> Refresh the page<br> Begin to input the same values again. Autocomplete will work on the name and telephone. It has been turned off for the address.</p> </body> </html>
By default, forms are submitted when the Enter key is pressed. Unless the form is being fully validated on the client-side, it is usually desirable to disable the Enter key.
Write code to disable the Enter key in a text input name as shown here.
Adjust the code above to include a second text input name as shown here. Hint: You can move the key pressed test to the form. This way, the function only has to be called once.
Adjust the code above to include other inputs as shown here. Because the key pressed function is called from the form, the additional inputs are automatically checked against the Enter key.
Adjust the code above to include a textarea in the form, as shown here. Note that the textarea needs to have the Enter key enabled, as it is used to place a linebreak in the textarea.
A JavaScript function can be called when a form is submitted. This function can be used to perform validation on the form data.
<script> <script>
function myFormValidationFunction()
{ // validate the form // return true if the form data is valid and false if the form data is not valid // If you return false, then the form will not be submitted ...
}
</script> <form action = "form_demo.html" onsubmit = "return myFormValidationFunction()"> ... </form>
The example below marks all of the fields that a user leaves blank.
Example of a Custom Submit Function (Run Example)
<!DOCTYPE html> <html> <head> <title>Course notes example code</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> let formHasNoErrors = true /* Each input element that needs to be validated needs its own validation function */ function isNameValid() { let errorMessage = "" // test to see if the name is not empty if (document.getElementById("name").value.length === 0) { errorMessage += "Please enter a name" } // passed all tests, so it is a valid name document.getElementById("nameErrorMessage").innerHTML = errorMessage return (errorMessage.length === 0) } function isAddressValid() { let errorMessage = "" // test to see if the address is not empty if (document.getElementById("address").value.length === 0) { errorMessage += "Please enter an address" } // passed all tests, so it is a valid address document.getElementById("addressErrorMessage").innerHTML = errorMessage return (errorMessage.length === 0) } /************************************************************************************/ /* The form needs one main wrapper function that will call each of the input element validation functions above */ function isFormValid() { /* Validate all of the input elements */ let nameIsValid = isNameValid() let addressIsValid = isAddressValid() /* If ALL of the element validation functions pass, then the form is valid */ if (nameIsValid && addressIsValid) { return true } else /* If ANY of the element validation functions fail, then the form fails */ { return false } } </script> </head> <body> <form action = "form_demo.html" onsubmit = "return isFormValid()"> <label for = "name">Name:</label><input type = "text" id = "name" name = "name"><label id = "nameErrorMessage"></label><br> <label for = "address">Address:</label><textarea rows = "5" id = "address" name = "address"></textarea><label id = "addressErrorMessage"></label><br> <input type = "submit"> </form> </body> </html>
Write code to validate a form that contains a name, address and phone number prior to submitting the form. All three fields must contain a value, the address must include at least two lines and the phone number must contain only digits and be seven digits long, as shown here.
Adjust the code above, so that the form checks for errors after each key input, as shown here. Use the javascript onkeyup() function to catch the key presses.
Adjust the code above, so that the form checks for errors after each key input, but only after the for has been submitted at least once, as shown here.
Copyright Derek O' Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.