0% found this document useful (0 votes)
30 views40 pages

HTML Form Note

The document provides a comprehensive overview of HTML forms, detailing various elements such as <form>, <input>, <label>, <select>, and <textarea>, along with their attributes and usage. It explains how to collect user input, submit data to a server, and the differences between GET and POST methods. Additionally, it covers various input types and their specific functions within forms.

Uploaded by

Prabin Magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views40 pages

HTML Form Note

The document provides a comprehensive overview of HTML forms, detailing various elements such as <form>, <input>, <label>, <select>, and <textarea>, along with their attributes and usage. It explains how to collect user input, submit data to a server, and the differences between GET and POST methods. Additionally, it covers various input types and their specific functions within forms.

Uploaded by

Prabin Magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

HTML Forms

<!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 <form> Element

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

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

<input type="text"> defines a single-line input field for text input.

A form with two text input 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.

The <label> Element

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

<input type="radio"> defines a radio button.

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>

The Submit Button

<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>

This is how the HTML code above will be displayed in a browser:


The Action Attribute

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

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

The method attribute specifies the HTTP method (GET or POST) to be used when submitting the form data.

Use the GET method when submitting the form:

<form action="/action_page.php" method="get">

or:

Use the POST method when submitting the form:

<form action="/action_page.php" method="post">

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:

 Appends form-data into the URL in name/value pairs


 The length of a URL is limited (2048 characters)
 Never use GET to send sensitive data! (will be visible in the URL)
 Useful for form submissions where a user wants to bookmark the result
 GET is better for non-secure data, like query strings in Google

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

The Name Attribute

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>

Here is the list of all <form> attributes:

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).

HTML Form Elements

This chapter describes all the different HTML form elements.

The <input> Element

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".

The <select> Element

The <select> element defines a drop-down list:

<h2>The select Element</h2>


<p>The select element defines a drop-down list:</p>

<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:

<option value="fiat" selected>Fiat</option>

Visible Values:

Use the size attribute to specify the number of visible values:

<select name="cars" size="3">


<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

Allow Multiple Selections:

Use the multiple attribute to allow the user to


select more than one value:

<select name="cars" size="4" multiple>


<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

The <textarea> Element

The <textarea> element defines a multi-line input field (a text area):

<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>

The <button> Element

The <button> element defines a clickable button:

<button type="button" onclick="alert('Hello World!')">Click Me!</button>

This is how the HTML code above will be displayed in a browser:

Note: Always specify the type attribute for the button element. Different browsers may use different default types for the
button element.

The <fieldset> and <legend> Elements

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>

The <datalist> Element

The <datalist> element specifies a list of pre-


defined options for an <input> element. Users
will see a drop-down list of the pre-defined
options as they input data. The list attribute of
the <input> element, must refer to
the id attribute of the <datalist> element.

<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

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:

<h2>The output Element</h2>


<p>The output element represents the result of a calculation.</p>

<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>

HTML Form Elements

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

HTML Input Types

This chapter describes the different input types for the <input> element.

HTML Input Types

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">

Input Type Text

<input type="text"> defines a single-line text input field:

<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>

Input Type Password

<input type="password"> defines a password field:

<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>

This is how the HTML code above will be displayed in a browser:

The characters in a password field are masked (shown as asterisks or circles).

Input Type Submit

<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

<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>

This is how the HTML code above will be displayed in a browser:

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

<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

<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>

This is how the HTML code above will be displayed in a browser:


Input Type Button

<input type="button"> defines a button:

<input type="button" onclick="alert('Hello World!')" value="Click Me!">

This is how the HTML code above will be displayed in a browser:

Input Type Color

The <input type="color"> is used for


input fields that should contain a color.
Depending on browser support, a color
picker can show up in the input field.

<form>
<label for="favcolor">Select your favorite color:</label>
<input type="color" id="favcolor" name="favcolor">
</form>

Input Type Date

The <input type="date"> is used for input


fields that should contain a date. Depending
on browser support, a date picker can show
up in the input field.

<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>

Input Type Email

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>

Input Type File

The <input type="file"> defines a file-select field and a "Browse" button for file uploads.

<p>Show a file-select field which allows a file to be chosen for upload:</p>


<form action="/action_page.php">
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile"><br><br>
<input type="submit" value="Submit">
</form>
Input Type Month

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>

Input Type Number

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>

Input Type Range

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" method="get">


<label for="vol">Volume (between 0 and 50):</label>
<input type="range" id="vol" name="vol" min="0" max="50">
<input type="submit" value="Submit">
</form>

Input Type Search


The <input type="search"> is used for search fields (a search field behaves like a regular text field).

<form action="/action_page.php">
<label for="gsearch">Search Google:</label>
<input type="search" id="gsearch" name="gsearch">
<input type="submit" value="Submit">
</form>

Input Type Tel

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>

Input Type Time

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>

Input Type Url

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>

Input Type Week

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>

HTML Input Attributes

The value Attribute

The input value attribute specifies an initial value for an input field:

Input fields with initial (default) values:

<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 readonly Attribute

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 disabled Attribute

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 size Attribute

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.

Set a width for an input field:

<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 maxlength Attribute

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.

Set a maximum length for an input field:

<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 min and max Attributes

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.

Set a max date, a min date, and a range of legal values:


<form>
<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>

<label for="quantity">Quantity (between 1 and 5):</label>


<input type="number" id="quantity" name="quantity" min="1" max="5">
</form>>

The multiple Attribute

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.

A file upload field that accepts multiple values:

<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 pattern Attribute

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.

Tip: Learn more about regular expressions in our JavaScript tutorial.

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 placeholder Attribute

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 required Attribute

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.

A required input field:

<form action="/action_page.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<input type="submit" value="Submit">
</form>

The step Attribute


The input step attribute specifies the legal number intervals for an input field. Example: if step="3", legal numbers could be -3,
0, 3, 6, etc.

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 autofocus Attribute

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 height and width Attributes

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:

<h1>The input height and width attributes</h1>


<p>The height and width attributes specify the height and width of an input type="image" element.</p>

<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 autocomplete Attribute

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:

<form action="/action_page.php" autocomplete="on">


<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>
<label for="email">Email:</label>
<input type="email" id="email" name="email" autocomplete="off"><br><br>
<input type="submit" value="Submit">
</form>
Tip: In some browsers you may need to activate an autocomplete function for this to work (Look under "Preferences" in the
browser's menu).

HTML Form and Input Elements

Tag Description
<form> Defines an HTML form for user input
<input> Defines an input control

HTML Input form* Attributes

The form Attribute

The input form attribute specifies the form


the <input> element belongs to. The value
of this attribute must be equal to the id
attribute of the <form> element it belongs
to. An input field located outside of the
HTML form (but still a part of the form):

<h1>The input form attribute</h1>


<p>The form attribute specifies the form an input element belongs to.</p>

<form action="/action_page.php" id="form1">


<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<input type="submit" value="Submit">
</form>

<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 formaction Attribute

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 formenctype Attribute

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 formmethod Attribute

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").

Notes on the "get" method:

 This method appends the form-data to the URL in name/value pairs


 This method is useful for form submissions where a user want to bookmark the result
 There is a limit to how much data you can place in a URL (varies between browsers), therefore, you cannot be sure
that all of the form-data will be correctly transferred
 Never use the "get" method to pass sensitive information! (password or other sensitive information will be visible in
the browser's address bar)

Notes on the "post" method:

 This method sends the form-data as an HTTP post transaction


 Form submissions with the "post" method cannot be bookmarked
 The "post" method is more robust and secure than "get", and "post" does not have size limitations

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 formtarget Attribute

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 formnovalidate Attribute

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

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 action="/action_page.php" novalidate>


<label for="email">Enter your email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>

JavaScript - Form Validation

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.

JavaScript Form Validation Example

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.

<form name = "myForm" onsubmit="return validateForm()">


Name: <input type = "text" name = "name"><br>
Password: <input type = "password" name = "password"><br>
<input type = "submit" value = "Register">
</form>

function validateForm(){
var name = document.myForm.name.value;
var password = document.myForm.password.value;

if(name == null || name == ""){


alert("Name can't be blank");
return false;
} else if(password.length < 6){
alert("Password must be at least 6 characters long.");
return false;
}
}

JavaScript Retype Password Validation

<form name = "f1" onsubmit="return matchPass()">


Password: <input type = "password" name = "password"> <br>
Re-enter password: <input type = "password" name = "password2"><br>
<input type = "submit" value = "Submit">
</form>

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.

<form name = "myForm" onsubmit="return validate()">


Number: <input type = "text" name = "num">
<span id = "numloc"></span><br>
<input type = "submit" value = "submit">
</form>

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.

<form name = "f1" onsubmit = "return validate()">


Enter Name: <input type = "text" name = "name">
<span id = "nameloc"></span>
<br>
Enter Password: <input type = "password" name = "password">
<span id = "passwordloc"></span>
<br>
<input type = "submit" value = "Register">
</form>

function validate(){
var name = document.f1.name.value;
var password = document.f1.password.value;
var status = false;

if(name.length < 1){


document.getElementById("nameloc").innerHTML = "<img src = 'incorrect.png'> Please enter your
name";
status = false;
} else {
document.getElementById("nameloc").innerHTML = "<img src = 'correct.png'>";
status = true;
}

if(password.length < 6){


document.getElementById("passwordloc").innerHTML = "<img src = 'incorrect.png'> Password must
be at least 6 char long";
status = false;
} else {
document.getElementById("passwordloc").innerHTML = "<img src = 'correct.png'>";
status = true;
}
return status;
}

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:

o email id must contain the @ and . character


o There must be at least one character before and after the @.
o There must be at least two characters after . (dot).

Let's see the simple example to validate the email field.

<form name = "myForm" onsubmit = "return validateEmail()">


Email: <input type = "text" name = "email"><br>
<input type = "submit" value = "Register">
</form>

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.

<form name = "myForm" onsubmit = "return(validate());">


<label for = "name">Name</label>
<input type = "text" id = "name" name = "Name">
<br>
<label for = "email">Email</label>
<input type = "text" id = "email" name = "EMail">
<br>
<label for = "zip-code">Zip Code</label>
<input type = "text" id = "zip-code" name = "Zip">
<br>
<label for = "country">Country</label>
<select id = "countries" name = "Country">
<option value = "-1" selected>(choose your)</option>
<option value = "1">USA</option>
<option value = "2">China</option>
<option value = "3">Australia</option>
<option value = "4">Japan</option>
</select>
<br>
<input type = "submit" value = "Submit">
</form>
function validate(){
if(document.myForm.Name.value == ""){
alert("Pelase provide your name!");
document.myForm.Name.focus();
return false;
}
if(document.myForm.EMail.value == ""){
alert("Please provide your Email!");
document.myForm.EMail.focus();
return false;
}

if(validateEmail()) return true;


else return false;

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;
}

Understanding Client-Side Validation

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:

// Defining a function to display error message


function printError(elemId, hintMsg) {
document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form


function validateForm() {
// Retrieving the values of form elements
var name = document.contactForm.name.value;
var email = document.contactForm.email.value;
var mobile = document.contactForm.mobile.value;
var country = document.contactForm.country.value;
var gender = document.contactForm.gender.value;
var hobbies = [];
var checkboxes = document.getElementsByName("hobbies[]");
for(var i=0; i < checkboxes.length; i++) {
if(checkboxes[i].checked) {
// Populate hobbies array with selected values
hobbies.push(checkboxes[i].value);
}
}

// Defining error variables with a default value


var nameErr = emailErr = mobileErr = countryErr = genderErr = true;

// 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 email address


if(email == "") {
printError("emailErr", "Please enter your email address");
} else {
// Regular expression for basic email validation
var regex = /^\S+@\S+\.\S+$/;
if(regex.test(email) === false) {
printError("emailErr", "Please enter a valid email address");
} else{
printError("emailErr", "");
emailErr = false;
}
}

// Validate mobile number


if(mobile == "") {
printError("mobileErr", "Please enter your mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if(regex.test(mobile) === false) {
printError("mobileErr", "Please enter a valid 10 digit mobile number");
} else{
printError("mobileErr", "");
mobileErr = 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.

JavaScript Regular Expressions

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.

What is Regular Expression?

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.

Function What it Does


exec() Search for a match in a string. It returns an array of information or null on mismatch.
test() Test whether a string matches a pattern. It returns true or false.
search() Search for a match within a string. It returns the index of the first match, or -1 if not found.
replace() Search for a match in a string, and replaces the matched substring with a replacement string.
match() Search for a match in a string. It returns an array of information or null on mismatch.
split() Splits up a string into an array of substrings using a regular expression.
Note: The methods exec() and test() are RegExp methods that takes a string as a parameter, whereas the
methods search(), replace(), match() and split() are String methods that takes a regular expression as a parameter.

Defining 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.

Pattern Matching with Regular Expression

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:

RegExp What it Does


[abc] Matches any one of the characters a, b, or c.
[^abc] Matches any one character other than a, b, or c.
[a-z] Matches any one character from lowercase a to lowercase z.
[A-Z] Matches any one character from uppercase a to uppercase z.
[a-Z] Matches any one character from lowercase a to uppercase Z.
[0-9] Matches a single digit between 0 and 9.
[a-z0-9] Matches a single character between a and z or between 0 and 9.

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:

var regex = /ca[kf]e/;


var str = "He was eating cake in the cafe.";

// Test the string against the regular expression


if(regex.test(str)) {
alert("Match found!");
} else {
alert("Match not found.");
}

Further, you can add the global flag g to a regular expression to find all matches in a string:

var regex = /ca[kf]e/g;


var str = "He was eating cake in the cafe.";
var matches = str.match(regex);
alert(matches.length); // Outputs: 2

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.

Predefined Character Classes

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:

Shortcut What it Does


. Matches any single character except newline \n.
\d matches any digit character. Same as [0-9]
\D Matches any non-digit character. Same as [^0-9]
\s Matches any whitespace character (space, tab, newline or carriage return character).
Same as [ \t\n\r]
\S Matches any non-whitespace character.
Same as [^ \t\n\r]
\w Matches any word character (definned as a to z, A to Z,0 to 9, and the underscore).
Same as [a-zA-Z_0-9]
\W Matches any non-word character. Same as [^a-zA-Z_0-9]

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:

var regex = /\s/g;


var replacement = "-";
var str = "Earth revolves around\nthe\tSun";
// Replace spaces, newlines and tabs
document.write(str.replace(regex, replacement) + "<hr>");

// Replace only spaces


document.write(str.replace(/ /g, "-"));

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:

RegExp What it Does


p+ Matches one or more occurrences of the letter p.
p* Matches zero or more occurrences of the letter p.
p? Matches zero or one occurrences of the letter p.
p{2} Matches exactly two occurrences of the letter p.
p{2,3} Matches at least two occurrences of the letter p, but not more than three occurrences.
p{2,} Matches two or more occurrences of the letter p.
p{,3} Matches at most three occurrences of the letter p

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:

var regex = /[\s,]+/;


var str = "My favourite colors are red, green and blue";
var parts = str.split(regex);

// Loop through parts array and display substrings


for(var part of parts){
document.write("<p>" + part + "</p>");
}

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.

RegExp What it Does


^p Matches the letter p at the beginning of a line.
p$ Matches the letter p at the end of a line.

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:

var regex = /^J/;


var names = ["James Bond", "Clark Kent", "John Rambo"];

// Loop through names array and display matched names


for(var name of names) {
if(regex.test(name)) {
document.write("<p>" + name + "</p>")
}
}

Pattern Modifiers (Flags)

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.

Modifier What it Does


g Perform a global match i.e. finds all occurrences.
i Makes the match case-insensitive manner.
m Changes the behavior of ^ and $ to match against a newline boundary (i.e. start or end of each line within a
multiline string), instead of a string boundary.
o Evaluates the expression only once.
s Changes the behavior of . (dot) to match all characters, including newlines.
x Allows you to use whitespace and comments within a regular expression for clarity.

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.

var regex = /color/gi;


var str = "Color red is more visible than color blue in daylight.";
var matches = str.match(regex); // global, case-insensitive match
console.log(matches);
// expected output: ["Color", "color"]

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.

var regex = /^color/gim;


var str = "Color red is more visible than \ncolor blue in daylight.";
var matches = str.match(regex); // global, case-insensitive, multiline match
console.log(matches);
// expected output: ["Color", "color"]

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:

var regex = /fox|dog|cat/;


var str = "The quick brown fox jumps over the lazy dog.";
var matches = str.match(regex);
console.log(matches);
// expected output: ["fox", index: 16, ...]

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.

var regex = /(go)+/i;


var str = "One day Gogo will go to school.";
var matches = str.match(regex); // case-insensitive match
console.log(matches);
// expected output: ["Gogo", "go", index: 8, ...]

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:

var regex = /(\bcar\w*)/g;


var str = "Words begining with car: cart, carrot, cartoon. Words ending with car: oscar, supercar.";
var replacement = '<b>$1</b>';
var result = str.replace(regex, replacement);
document.write(result);
HTML Semantic Elements

Semantic elements = elements with a meaning.

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.

<p>My family and I visited The Epcot center this summer.</p>


<aside>
<h4>Epcot Center</h4>
<p>The Epcot Center is a theme park in Disney World, Florida.</p>
</aside>

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."

You might also like