HTML Form Note
HTML Form Note
<!DOCTYPE html>
<html>
<body>
<h2>HTML Forms</h2>
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><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>
</body>
</html>
The HTML <form> element defines a form that is used to collect user input:
<form>
.
form elements
.
</form>
An HTML form contains form elements. Form elements are different types of input elements, like: text fields, checkboxes,
radio buttons, submit buttons, and more.
The <input> element is the most important form element. The <input> element is displayed in several ways, depending on
the type attribute. Here are some examples:
Type Description
<input type="text"> Defines a single-line text input field
<input type="radio"> Defines a radio button (for selecting one of many choices)
<input type="submit"> Defines a submit button (for submitting the form)
Text Fields
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
Note: The form itself is not visible. Also note that the default width of an input field is 20 characters.
Notice the use of the <label> element in the example above. The <label> tag defines a label for many form elements.
The <label> element is useful for screen-reader users, because the screen-reader will read out load the label when the user is
focused on the input element. The <label> element also help users who have difficulty clicking on very small regions (such as
radio buttons or checkboxes) - because when the user clicks the text within the <label> element, it toggles the radio
button/checkbox.
The for attribute of the <label> tag should be equal to the id attribute of the <input> element to bind them together.
Radio Buttons
Radio buttons let a user select ONE of a limited number of choices. A form with radio buttons:
<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>
<input type="submit"> defines a button for submitting the form data to a form-handler. The form-handler is typically a page
on the server with a script for processing input data. The form-handler is specified in the form's action attribute. A form with a
submit button:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
The action attribute defines the action to be performed when the form is submitted. Usually, the form data is sent to a page on
the server when the user clicks on the submit button. In the example above, the form data is sent to a page on the server
called "/action_page.php". This page contains a server-side script that handles the form data:
<form action="/action_page.php">
If the action attribute is omitted, the action is set to the current page.
The target attribute specifies if the submitted result will open in a new browser tab, a frame, or in the current window. The
default value is "_self" which means the form will be submitted in the current window. To make the form result open in a new
browser tab, use the value "_blank".
Here, the submitted result will open in a new browser tab: <form action="/action_page.php" target="_blank">
Other legal values are "_parent", "_top", or a name representing the name of an iframe.
The method attribute specifies the HTTP method (GET or POST) to be used when submitting the form data.
or:
When to Use GET? The default HTTP method when submitting form data is GET. However, when GET is used, the form data
will be visible in the page's address field: /action_page.php?firstname=John&lastname=Doe
Notes on GET:
When to Use POST? Always use POST if the form data contains sensitive or personal information. The POST method does not
display the form data in the page address field.
Notes on POST:
POST has no size limitations, and can be used to send large amounts of data.
Form submissions with POST cannot be bookmarked
Each input field must have a name attribute to be submitted. If the name attribute is omitted, the data of that input field will
not be sent at all. This example will not submit the value of the "First name" input field:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" value="John"><br><br>
<input type="submit" value="Submit">
</form>
Attribute Description
accept-charset Specifies the charset used in the submitted form (default: the page charset).
action Specifies an address (url) where to submit the form (default: the submitting page).
autocomplete Specifies if the browser should autocomplete the form (default: on).
enctype Specifies the encoding of the submitted data (default: is url-encoded).
method Specifies the HTTP method used when submitting the form (default: GET).
name Specifies a name used to identify the form (for DOM usage: document.forms.name).
novalidate Specifies that the browser should not validate the form.
target Specifies the target of the address in the action attribute (default: _self).
One of the most used form element is the <input> element. The <input> element can be displayed in several ways, depending
on the type attribute.
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br><br>
<input type="submit" value="Submit">
</form>
If the type attribute is omitted, the input field gets the default type: "text".
<form action="/action_page.php">
<label for="cars">Choose a car:</label>
<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
The <option> elements defines an option that can be selected. By default, the first item in the drop-down list is selected. To
define a pre-selected option, add the selected attribute to the option:
Visible Values:
<form action="/action_page.php">
<textarea name="message" rows="10" cols="30">The cat
was playing in the garden.</textarea>
<br><br>
<input type="submit">
</form>
The rows attribute specifies the visible number of lines in a text area.
The cols attribute specifies the visible width of a text area. This is
how the HTML code above will be displayed in a browser:
You can also define the size of the text area by using CSS:
<textarea name="message" style="width:200px; height:600px;">
The cat was playing in the garden.
</textarea>
Note: Always specify the type attribute for the button element. Different browsers may use different default types for the
button element.
The <fieldset> element is used to group related data in a form. The <legend> element defines a caption for
the <fieldset> element.
<form action="/action_page.php">
<fieldset>
<legend>Personalia:</legend>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<form action="/action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
The <output> element represents the result of a calculation (like one performed by a script). Perform a calculation and show
the result in an <output> element:
<form action="/action_page.php"
oninput="x.value=parseInt(a.value)+parseInt(b.value)">
0
<input type="range" id="a" name="a" value="50">
100 +
<input type="number" id="b" name="b" value="50">
=
<output name="x" for="a b"></output>
<br><br>
<input type="submit">
</form>
<p><strong>Note:</strong> The output element is not supported in Edge prior version 13.</p>
Tag Description
<form> Defines an HTML form for user input
<input> Defines an input control
<textarea> Defines a multiline input control (text area)
<label> Defines a label for an <input> element
<fieldset> Groups related elements in a form
<legend> Defines a caption for a <fieldset> element
<select> Defines a drop-down list
<optgroup> Defines a group of related options in a drop-down list
<option> Defines an option in a drop-down list
<button> Defines a clickable button
<datalist> Specifies a list of pre-defined options for input controls
<output> Defines the result of a calculation
This chapter describes the different input types for the <input> element.
Here are the different input types you can use in HTML:
<input type="button">
<input type="checkbox">
<input type="color">
<input type="date">
<input type="datetime-local">
<input type="email">
<input type="file">
<input type="hidden">
<input type="image">
<input type="month">
<input type="number">
<input type="password">
<input type="radio">
<input type="range">
<input type="reset">
<input type="search">
<input type="submit">
<input type="tel">
<input type="text">
<input type="time">
<input type="url">
<input type="week">
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
<form>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd" name="pwd">
</form>
<input type="submit"> defines a button for submitting form data to a form-handler. The form-handler is typically a server
page with a script for processing input data. The form-handler is specified in the
form's action attribute:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
If you omit the submit button's value attribute, the button will get a default text:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit">
</form>
<input type="reset"> defines a reset button that will reset all form values to their default values:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
<input type="reset">
</form>
If you change the input values and then click the "Reset" button, the form-data will be reset to the default values.
<input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE of a limited number of choices:
<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>
<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE options of a limited number of
choices.
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>
<form>
<label for="favcolor">Select your favorite color:</label>
<input type="color" id="favcolor" name="favcolor">
</form>
<form action="/action_page.php">
<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday">
<input type="submit" value="Submit">
</form>
You can also use the min and max attributes to add restrictions to dates:
<form action="/action_page.php">
<label for="datemax">Enter a date before 1980-01-01:</label>
<input type="date" id="datemax" name="datemax" max="1979-12-31"><br><br>
<label for="datemin">Enter a date after 2000-01-01:</label>
<input type="date" id="datemin" name="datemin" min="2000-01-02"><br><br>
<input type="submit" value="Submit">
</form>
Input Type Datetime-local
The <input type="datetime-local"> specifies a date and time input field, with no time zone. Depending on browser support, a
date picker can show up in the input field.
<form action="/action_page.php">
<label for="birthdaytime">Birthday (date and time):</label>
<input type="datetime-local" id="birthdaytime" name="birthdaytime">
<input type="submit" value="Submit">
</form>
The <input type="email"> is used for input fields that should contain an e-mail address. Depending on browser support, the e-
mail address can be automatically validated when submitted. Some smartphones recognize the email type, and add ".com" to
the keyboard to match email input.
<form action="/action_page.php">
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email">
<input type="submit" value="Submit">
</form>
The <input type="file"> defines a file-select field and a "Browse" button for file uploads.
The <input type="month"> allows the user to select a month and year. Depending on browser support, a date picker can show
up in the input field.
<form action="/action_page.php">
<label for="bdaymonth">Birthday (month and year):</label>
<input type="month" id="bdaymonth" name="bdaymonth">
<input type="submit" value="Submit">
</form>
The <input type="number"> defines a numeric input field. You can also set restrictions on what numbers are accepted. The
following example displays a numeric input field, where you can enter a value from 1 to 5:
<form action="/action_page.php">
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
<input type="submit" value="Submit">
</form>
Input Restrictions - Here is a list of some common input restrictions:
Attribute Description
checked Specifies that an input field should be pre-selected when the page loads (for type="checkbox" or
type="radio")
disabled Specifies that an input field should be disabled
max Specifies the maximum value for an input field
maxlength Specifies the maximum number of character for an input field
min Specifies the minimum value for an input field
pattern Specifies a regular expression to check the input value against
readonly Specifies that an input field is read only (cannot be changed)
required Specifies that an input field is required (must be filled out)
size Specifies the width (in characters) of an input field
step Specifies the legal number intervals for an input field
value Specifies the default value for an input field
The following example displays a numeric input field, where you can enter a value from 0 to 100, in steps of 10. The default
value is 30:
<form action="/action_page.php">
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" min="0" max="100"
step="10" value="30">
<input type="submit" value="Submit">
</form>
The <input type="range"> defines a control for entering a number whose exact value is not important (like a slider control).
Default range is 0 to 100. However, you can set restrictions on what numbers are accepted with the min, max,
and step attributes:
<form action="/action_page.php">
<label for="gsearch">Search Google:</label>
<input type="search" id="gsearch" name="gsearch">
<input type="submit" value="Submit">
</form>
The <input type="tel"> is used for input fields that should contain a telephone number.
<form action="/action_page.php">
<label for="phone">Enter a phone number:</label><br><br>
<input type="tel" id="phone" name="phone" placeholder="123-45-678" pattern="[0-9]{3}-[0-9]{2}-[0-
9]{3}" required><br><br>
<small>Format: 123-45-678</small><br><br>
<input type="submit" value="Submit">
</form>
The <input type="time"> allows the user to select a time (no time zone). Depending on browser support, a time picker can
show up in the input field.
<form action="/action_page.php">
<label for="appt">Select a time:</label>
<input type="time" id="appt" name="appt">
<input type="submit" value="Submit">
</form>
The <input type="url"> is used for input fields that should contain a URL address. Depending on browser support, the url field
can be automatically validated when submitted. Some smartphones recognize the url type, and adds ".com" to the keyboard to
match url input.
<form action="/action_page.php">
<label for="homepage">Add your homepage:</label>
<input type="url" id="homepage" name="homepage">
<input type="submit" value="Submit">
</form>
The <input type="week"> allows the user to select a week and year. Depending on browser support, a date picker can show
up in the input field.
<form action="/action_page.php">
<label for="week">Select a week:</label>
<input type="week" id="week" name="week">
<input type="submit" value="Submit">
</form>
The input value attribute specifies an initial value for an input field:
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>
The input readonly attribute specifies that an input field is read-only. A read-only input field cannot be modified (however, a
user can tab to it, highlight it, and copy the text from it). The value of a read-only input field will be sent when submitting the
form! A read-only input field:
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John" readonly><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>
The input disabled attribute specifies that an input field should be disabled. A disabled input field is unusable and un-clickable.
The value of a disabled input field will not be sent when submitting the form! A disabled input field:
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John" disabled><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>
The input size attribute specifies the visible width, in characters, of an input field. The default value for size is 20.
Note: The size attribute works with the following input types: text, search, tel, url, email, and password.
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" size="50"><br>
<label for="pin">PIN:</label><br>
<input type="text" id="pin" name="pin" size="4">
</form>
The input maxlength attribute specifies the maximum number of characters allowed in an input field.
Note: When a maxlength is set, the input field will not accept more than the specified number of characters. However, this
attribute does not provide any feedback. So, if you want to alert the user, you must write JavaScript code.
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" size="50"><br>
<label for="pin">PIN:</label><br>
<input type="text" id="pin" name="pin" maxlength="4" size="4">
</form>
The input min and max attributes specify the minimum and maximum values for an input field. The min and max attributes
work with the following input types: number, range, date, datetime-local, month, time and week. Tip: Use the max and min
attributes together to create a range of legal values.
The input multiple attribute specifies that the user is allowed to enter more than one value in an input field.
The multiple attribute works with the following input types: email, and file.
<form action="/action_page.php">
<label for="files">Select files:</label>
<input type="file" id="files" name="files" multiple><br><br>
<input type="submit" value="Submit">
</form>
The input pattern attribute specifies a regular expression that the input field's value is checked against, when the form is
submitted. The pattern attribute works with the following input types: text, date, search, url, tel, email, and password.
Tip: Use the global title attribute to describe the pattern to help the user.
An input field that can contain only three letters (no numbers or special characters):
<form action="/action_page.php">
<label for="country_code">Country code:</label>
<input type="text" id="country_code" name="country_code" pattern="[A-Za-z]{3}" title="Three letter
country code"><br><br>
<input type="submit" value="Submit">
</form>
The input placeholder attribute specifies short a hint that describes the expected value of an input field (a sample value or a
short description of the expected format).
The short hint is displayed in the input field before the user enters a value. The placeholder attribute works with the following
input types: text, search, url, tel, email, and password. An input field with a placeholder text:
<form action="/action_page.php">
<label for="phone">Enter a phone number:</label>
<input type="tel" id="phone" name="phone" placeholder="123-45-678" pattern="[0-9]{3}-[0-9]{2}-[0-
9]{3}"><br><br>
<input type="submit" value="Submit">
</form>
The input required attribute specifies that an input field must be filled out before submitting the form. The required attribute
works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
<form action="/action_page.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<input type="submit" value="Submit">
</form>
Tip: This attribute can be used together with the max and min attributes to create a range of legal values.
The step attribute works with the following input types: number, range, date, datetime-local, month, time and week. An input
field with a specified legal number intervals:
<form action="/action_page.php">
<label for="points">Points:</label>
<input type="number" id="points" name="points" step="3">
<input type="submit" value="Submit">
</form>
Note: Input restrictions are not foolproof, and JavaScript provides many ways to add illegal input. To safely restrict input, it
must also be checked by the receiver (the server)!
The input autofocus attribute specifies that an input field should automatically get focus when the page loads. Let the "First
name" input field automatically get focus when the page loads:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" autofocus><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>
The input height and width attributes specify the height and width of an <input type="image"> element.
Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the
image is reserved when the page is loaded. Without these attributes, the browser does not know the size of the image, and
cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the images
load).
Define an image as the submit button, with height and width attributes:
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="image" src="img_submit.gif" alt="Submit" width="48" height="48">
</form>
<p><b>Note:</b> The input type="image" sends the X and Y coordinates of the click that activated the
image button.</p>
The list Attribute
The input list attribute refers to a <datalist> element that contains pre-defined options for an <input> element. An <input>
element with pre-defined values in a <datalist>:
<form action="/action_page.php">
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet
Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
<input type="submit"
value="Submit">
</form>
The input autocomplete attribute specifies whether a form or an input field should have autocomplete on or off. Autocomplete
allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the
field, based on earlier typed values.
The autocomplete attribute works with <form> and the following <input> types: text, search, url, tel, email, password,
datepickers, range, and color.
An HTML form with autocomplete on, and off for one input field:
Tag Description
<form> Defines an HTML form for user input
<input> Defines an input control
<p>The "Last name" field below is outside the form element, but still part of the form.</p>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" form="form1">
The input formaction attribute specifies the URL of the file that will process the input when the form is submitted. Note: This
attribute overrides the action attribute of the <form> element. The formaction attribute works with the following input types:
submit and image. An HTML form with two submit buttons, with different actions:
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
<input type="submit" formaction="/action_page2.php" value="Submit as Admin">
</form>
The input formenctype attribute specifies how the form-data should be encoded when submitted (only for forms with
method="post"). Note: This attribute overrides the enctype attribute of the <form> element.
The formenctype attribute works with the following input types: submit and image. A form with two submit buttons. The first
sends the form-data with default encoding, the second sends the form-data encoded as "multipart/form-data":
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
<input type="submit" formaction="/action_page2.php" value="Submit as Admin">
</form>
The input formmethod attribute defines the HTTP method for sending form-data to the action URL. Note: This attribute
overrides the method attribute of the <form> element.
The formmethod attribute works with the following input types: submit and image. The form-data can be sent as URL variables
(method="get") or as an HTTP post transaction (method="post").
A form with two submit buttons. The first sends the form-data with method="get". The second sends the form-data with
method="post":
<form action="/action_page.php" method="get" target="_blank">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit using GET">
<input type="submit" formmethod="post" value="Submit using POST">
</form>
The input formtarget a attribute specifies a name or a keyword that indicates where to display the response that is received
after submitting the form. Note: This attribute overrides the target attribute of the <form> element.
The formtarget attribute works with the following input types: submit and image. A form with two submit buttons, with
different target windows:
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
<input type="submit" formtarget="_blank" value="Submit to a new window/tab">
</form>
The input formnovalidate attribute specifies that an <input> element should not be validated when submitted. Note: This
attribute overrides the novalidate attribute of the <form> element. The formnovalidate attribute works with the following input
types: submit. A form with two submit buttons (with and without validation):
<form action="/action_page.php">
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
<input type="submit" formnovalidate="formnovalidate"
value="Submit without validation">
</form>
The novalidate attribute is a <form> attribute. When present, novalidate specifies that all of the form-data should not be
validated when submitted. Specify that no form-data should be validated on submit:
Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the
Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data
back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which
used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation
generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would
require just a loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must
include appropriate logic to test correctness of data.
In this example, we are going to validate the name and password. The name can’t be empty and password can’t be less than 6
characters long. Here, we are validating the form on form submit. The user will not be forwarded to the next page until given
values are correct.
function validateForm(){
var name = document.myForm.name.value;
var password = document.myForm.password.value;
function matchPass(){
var firstPassword = document.f1.password.value;
var secondPassword = document.f1.password2.value;
if(firstPassword == secondPassword){
return true;
} else {
alert("Password must be same!");
return false;
}
}
JavaScript Number Validation - Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
function validate(){
var num = document.myForm.num.value;
if(isNaN(num)){
document.getElementById("numloc").innerHTML = "Enter Numeric value only";
}
}
JavaScript validation with image - Let’s see an interactive JavaScript form validation example that displays correct and
incorrect image if input is correct or incorrect.
function validate(){
var name = document.f1.name.value;
var password = document.f1.password.value;
var status = false;
JavaScript email validation - We can validate the email by the help of JavaScript. There are many criteria that need to be
follow to validate the email id such as:
function validateEmail(){
var x = document.myForm.email.value;
var atPosition = x.indexOf("@");
var dotPosition = x.indexOf(".");
if(atPosition < 1 || dotPosition < atPosition + 2 || dotPosition + 2 >= x.length){
alert("Please enter a valid e-mail address \n atposition: " + atPosition + "\n dotposition: "
+ dotPosition);
return false;
}
}
Example - We will take an example to understand the process of validation. Here is a simple form in html format.
function validateEmail(){
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf('@');
dotpos = emailID.indexOf('.');
if(atpos < 1 || (dotpos - atpos < 2)){
alert("Please enter correct email ID");
document.myForm.EMail.focus();
return false;
}
return true;
}
if(document.myForm.Zip.value == ""
|| isNaN(document.myForm.Zip.value)
|| document.myForm.Zip.value.length != 5){
alert("Please provide a zip in the format #####.");
document.myForm.Zip.focus();
return false;
}
if(document.myForm.Country.value == "-1"){
alert("Please select your country!");
return false;
}
return true;
}
Web forms have become an essential part of web applications. It is often used to collect user's information such as name,
email address, location, age, and so on. But it is quite possible that some user might not enter the data what you've expected.
So to save bandwidth and avoid unnecessary strain on your server resources you can validate the form data on client-side (i.e.
user's system) using JavaScript before passing it onto the web server for further processing.
Client-side validation is also helpful in creating better user experience, since it is faster because validation occurs within the
user's web browser, whereas server-side validation occurs on the server, which require user's input to be first submitted and
sent to the server before validation occurs, also user has to wait for server response to know what exactly went wrong.
In the following section we will take a closer look at how to perform JavaScript form validation and handle any input errors
found appropriately and gracefully.
Note: Client-side validation is not a substitute or alternative for server-side validation. You should always validate form data on
the server-side even if they are already validated on the client-side, because user can disable JavaScript in their browser.
Form Validation with JavaScript - The form validation process typically consists of two parts— the required fields
validation which is performed to make sure that all the mandatory fields are filled in, and the data format validation which is
performed to ensure that the type and format of the data entered in the form is valid. Well, let's get straight to it and see how
this actually works.
Creating the HTML Form - Let's first create a simple HTML form that we will validate on client-side using JavaScript when the
user clicks on the submit button. Well, let's create an HTML file named "application-form.html" and place the following code in
it, then save it somewhere on your system.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple HTML Form</title>
<link rel="stylesheet" href="style.css">
<script src="validator.js"></script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()" action="confirmation.php" method="post">
<h2>Application Form</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="error" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="error" id="emailErr"></div>
</div>
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile" maxlength="10">
<div class="error" id="mobileErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Australia</option>
<option>India</option>
<option>United States</option>
<option>United Kingdom</option>
</select>
<div class="error" id="countryErr"></div>
</div>
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
</div>
<div class="error" id="genderErr"></div>
</div>
<div class="row">
<label>Hobbies <i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
<label><input type="checkbox" name="hobbies[]" value="movies"> Movies</label>
<label><input type="checkbox" name="hobbies[]" value="music"> Music</label>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</body>
</html><!DOCTYPE html>
Building the Form Validation Script - Now we're going to create a JavaScript file that holds our complete validation script.
Well, let's create a JavaScript file named "validator.js" and place the following code inside it, then save it at the same location
where you've saved the previous HTML file. Go through each line of the following example code to understand how JavaScript
validation works:
// Validate name
if(name == "") {
printError("nameErr", "Please enter your name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if(regex.test(name) === false) {
printError("nameErr", "Please enter a valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}
// Validate country
if(country == "Select") {
printError("countryErr", "Please select your country");
} else {
printError("countryErr", "");
countryErr = false;
}
// Validate gender
if(gender == "") {
printError("genderErr", "Please select your gender");
} else {
printError("genderErr", "");
genderErr = false;
}
// Prevent the form from being submitted if there are any errors
if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
return false;
} else {
// Creating a string from input data for preview
var dataPreview = "You've entered the following details: \n" +
"Full Name: " + name + "\n" +
"Email Address: " + email + "\n" +
"Mobile Number: " + mobile + "\n" +
"Country: " + country + "\n" +
"Gender: " + gender + "\n";
if(hobbies.length) {
dataPreview += "Hobbies: " + hobbies.join(", ");
}
// Display input data in a dialog box before submitting the form
alert(dataPreview);
}
};
The value of an individual form field can be accessed and retrieved using the syntax:
document.formName.fieldName.value or document.getElementsByName(name).value.
But, to get the values from a form field that supports multiple selections, like a group of checkboxes, you need to utilize
the loop statement as shown in the example above (line no-14 to 21).
Also, to check whether the format of input data is correct or not we've used the regular expressions. It is one of the most
effective techniques for validating the user inputs.
Furthermore, the above script will also display the data entered by the user in an alert dialog box for preview purpose before
submitting the form to the web server.
Tip: However, you can validate email format using regular expression. But a user might enter an email that is correctly
formatted but does not exist. So for authentic email validation, send confirmation email to the user and verify whether the
email really exists or not.
Adding Style Sheet to Beautify the Form - Finally, create the file named "style.css" and place the following code in it, then
save it also at the same location where you've saved the previous two files. These are the style rules to beautify our form.
body {
font-size: 16px;
background: #f9f9f9;
font-family: "Segoe UI", "Helvetica Neue",
Arial, sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
form {
width: 300px;
background: #fff;
padding: 15px 40px 40px;
border: 1px solid #ccc;
margin: 50px auto 0;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px
}
label i {
color: #999;
font-size: 80%;
}
input, select {
border: 1px solid #ccc;
padding: 10px;
display: block;
width: 100%;
box-sizing: border-box;
border-radius: 2px;
}
.row {
padding-bottom: 10px;
}
.form-inline {
border: 1px solid #ccc;
padding: 8px 10px 4px;
border-radius: 2px;
}
.form-inline label, .form-inline input {
display: inline-block;
width: auto;
padding-right: 15px;
}
.error {
color: red;
font-size: 90%;
}
input[type="submit"] {
font-size: 110%;
font-weight: 100;
background: #006dcc;
border-color: #016BC1;
box-shadow: 0 3px 0 #0165b6;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #0165b6;
}
That's all, now open the "application-form.html" file in a web browser and try to fill some data and see how the script respond
when an invalid data is entered in a form field.
In this tutorial you will learn how regular expressions work, as well as how to use them to perform pattern matching in an
efficient way in JavaScript.
Regular Expressions, commonly known as "regex" or "RegExp", are a specially formatted text strings used to find patterns in
text. Regular expressions are one of the most powerful tools available today for effective and efficient text processing and
manipulations. For example, it can be used to verify whether the format of data i.e. name, email, phone number, etc. entered by
the user is correct or not, find or replace matching string within text content, and so on.
JavaScript supports Perl style regular expressions. Why Perl style regular expressions? Because Perl (Practical Extraction and
Report Language) was the first mainstream programming language that provided integrated support for regular expressions
and it is well known for its strong support of regular expressions and its extraordinary text processing and manipulation
capabilities.
Let's begin with a brief overview of the commonly used JavaScript's built-in methods for performing pattern-matching before
delving deep into the world of regular expressions.
In JavaScript, regular expressions are represented by RegExp object, which is a native JavaScript object like String, Array, and so
on. There are two ways of creating a new RegExp object — one is using the literal syntax, and the other is using
the RegExp() constructor.
The literal syntax uses forward slashes (/pattern/) to wrap the regular expression pattern, whereas the constructor syntax uses
quotes ("pattern"). The following example demonstrates both ways of creating a regular expression that matches any string
that begins with "Mr.".
// Literal syntax
var regex = /^Mr\./;
// Constructor syntax
var regex = new RegExp("^Mr\\.");
As you can see, the regular expression literal syntax is shorter and easier to read. Therefore it is preferable to use the literal
syntax. We'll also use it throughout this tutorial.
Note: When using the constructor syntax, you've to double-escape special characters, which means to match "." you need to
write "\\." instead of "\.". If there is only one backslash, it would be interpreted by JavaScript's string parser as an escaping
character and removed.
Regular expression patterns include the use of letters, digits, punctuation marks, etc., plus a set of special regular expression
characters (do not confuse with the HTML special characters).
The characters that are given special meaning within a regular expression, are:
. * ? + [ ] ( ) { } ^ $ | \. You will need to backslash these characters whenever you want to use them literally. For example, if you
want to match ".", you'd have to write \.. All other characters automatically assume their literal meanings.
The following sections describe the various options available for formulating patterns:
Character Classes
Square brackets surrounding a pattern of characters are called a character class e.g. [abc]. A character class always matches a
single character out of a list of specified characters that means the expression [abc] matches only a, b or c character.
Negated character classes can also be defined that match any character except those contained within the brackets. A negated
character class is defined by placing a caret (^) symbol immediately after the opening bracket, like [^abc], which matches any
character except a, b, and c.
You can also define a range of characters by using the hyphen (-) character inside a character class, like [0-9]. Let's look at
some examples of the character classes:
The following example will show you how to find whether a pattern exists within a string or not using the regular expression
with the JavaScript test() method:
Further, you can add the global flag g to a regular expression to find all matches in a string:
Tip: Regular expressions aren't exclusive to JavaScript. Languages such as Java, Perl, Python, PHP, etc. use the same notation
for finding patterns in text.
Some character classes such as digits, letters, and whitespaces are used so frequently that there are shortcut names for them.
The following table lists those predefined character classes:
The following example will show you how to find and replace space with a hyphen character in a string using regular
expression with the JavaScript replace() method:
Repetition Quantifiers
In the previous section we've learnt how to match a single character in a variety of fashions. But what if you want to match on
more than one character? For example, let's say you want to find out words containing one or more instances of the letter p, or
words containing at least two p's, and so on.
This is where quantifiers come into play. With quantifiers you can specify how many times a character in a regular expression
should match. Quantifiers can be applied to the individual characters, as well as classes of characters, and groups of
characters contained by the parentheses.
The following table lists the various ways to quantify a particular pattern:
The regular expression in the following example will splits the string at comma, sequence of commas, whitespace, or
combination thereof using the JavaScript split() method:
Position Anchors
There are certain situations where you want to match at the beginning or end of a line, word, or string. To do this you can use
anchors. Two common anchors are caret (^) which represent the start of the string, and the dollar ($) sign which represent the
end of the string.
The regular expression in the following example will match only those names in the names array which start with the letter "J"
using the JavaScript test() function:
A pattern modifier allows you to control the way a pattern match is handled. Pattern modifiers are placed directly after the
regular expression, for example, if you want to search for a pattern in a case-insensitive manner, you can use the i modifier, like
this: /pattern/i.
The following table lists some of the most commonly used pattern modifiers.
The following example will show you how to use the g and i modifiers in a regular expression to perform a global and case-
insensitive search with the JavaScript match() method.
Similarly, the following example shows how to match at the beginning of every line in a multi-line string using the ^ anchor
and m modifier with the JavaScript match() method.
Alternation
Alternation allows you to specify alternative version of a pattern. Alternation in a regular expression works just like
the OR operator in an if-else conditional statement.
You can specify alternation using a vertical bar (|). For example, the regexp /fox|dog|cat/ matches the string "fox", or the string
"dog", or the string "cat". Here's an example:
Note: Alternatives are evaluated from left to right until a match is found. If the left alternative matches, the right alternative is
ignored completely even if it has a match.
Grouping
Regular expressions use parentheses to group subexpressions, just like mathematical expressions. Parentheses allow
a repetition quantifier to be applied to an entire subexpression.
For example, in regexp /go+/ the quantifier + is applied only to the last character o and it matches the strings "go", "goo", and
so on. Whereas, in regexp /(go)+/ the quantifier + is applied to the group of characters g and o and it matches the strings
"go", "gogo", and so on.
Note: If the string matches the pattern, the match() method returns an array containing the entire matched string as the first
element, followed by any results captured in parentheses, and the index of the whole match. If no matches were found, it
returns null.
Tip: If the regular expression includes the g flag, the match() method only returns an array containing all matched substrings
rather than match object. Captured groups, index of the whole match, and other properties are not returned.
Word Boundaries
A word boundary character ( \b) helps you search for the words that begins and/or ends with a pattern. For example, the
regexp /\bcar/ matches the words beginning with the pattern car, and would match cart, carrot, or cartoon, but would not
match oscar.
Similarly, the regexp /car\b/ matches the words ending with the pattern car, and would match oscar or supercar, but would not
match cart. Likewise, the /\bcar\b/ matches the words beginning and ending with the pattern car, and would match only the
word car.
The following example will highlight the words beginning with car in bold:
What are Semantic Elements? A semantic element clearly describes its meaning to both the browser and the developer.
Examples of non-semantic elements: <div> and <span> - Tells nothing about its content. Examples
of semantic elements: <form>, <table>, and <article> - Clearly defines its content.
Semantic Elements in HTML - Many web sites contain HTML code like: <div id="nav"> <div
class="header"> <div id="footer"> to indicate navigation, header, and footer. In HTML there are
some semantic elements that can be used to define different parts of a web page: <article>,
<aside>, <details>, <figcaption>, <figure>, <footer>, <header>, <main>, <mark>, <nav>,
<section>, <summary>, <time>
HTML <section> Element - The <section> element defines a section in a document. According
to W3C's HTML documentation: "A section is a thematic grouping of content, typically with a
heading." A home page could normally be split into sections for introduction, content, and contact
information.
<section>
<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is....</p>
</section>
HTML <article> Element - The <article> element specifies independent, self-contained content. An article should make sense
on its own, and it should be possible to read it independently from the rest of the web site. Examples of where
an <article> element can be used:
Forum post
Blog post
Newspaper article
<article>
<h1>What Does WWF Do?</h1>
<p>WWF's mission is to stop the degradation of our planet's natural environment,
and build a future in which humans live in harmony with nature.</p>
</article>
Nesting <article> in <section> or Vice Versa? The<article> element specifies independent, self-contained content.
The <section> element defines section in a document. Can we use the definitions to decide how to nest those elements? No,
we cannot! So, on the Internet, you will find HTML pages with <section> elements containing <article> elements,
and <article> elements containing <section> elements. You will also find pages with <section> elements
containing <section> elements, and <article> elements containing <article> elements.
Example for a newspaper: The sport <article> in the sport section, may have a technical section in each <article>.
HTML <header> Element - The <header> element specifies a header for a document or section. The <header> element
should be used as a container for introductory content. You can have several <header> elements in one document. The
following example defines a header for an article:
<article>
<header>
<h1>What Does WWF Do?</h1>
<p>WWF's mission:</p>
</header>
<p>WWF's mission is to stop the degradation of our planet's natural environment,
and build a future in which humans live in harmony with nature.</p>
</article>
HTML <footer> Element - The <footer> element specifies a footer for a document or section. A <footer> element should
contain information about its containing element. A footer typically contains the author of the document, copyright
information, links to terms of use, contact information, etc. You may have several <footer> elements in one document.
<footer>
<p>Posted by: Hege Refsnes</p>
<p>Contact information: <a href="mailto:[email protected]">
[email protected]</a>.</p>
</footer>
HTML <nav> Element - The <nav> element defines a set of navigation links. Notice that NOT all links of a document should
be inside a <nav> element. The <nav> element is intended only for major block of navigation links.
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>
HTML <aside> Element - The <aside> element defines some content aside from the content it is placed in (like a sidebar).
The <aside> content should be related to the surrounding content.
HTML <figure> and <figcaption> Elements - An image and a caption can be grouped together in a <figure> element. The
purpose of a caption is to add a visual explanation to an image.
<figure>
<img src="pic_trulli.jpg" alt="Trulli">
<figcaption>Fig1. - Trulli, Puglia, Italy.</figcaption>
</figure>
The <img> element defines the image, the <figcaption> element defines the caption.
Why Semantic Elements? According to the W3C: "A semantic Web allows data to be shared and reused across applications,
enterprises, and communities."