0% found this document useful (0 votes)
13 views

IWD Lecture 3 Forms and Client-Side Validation-2

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

IWD Lecture 3 Forms and Client-Side Validation-2

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

Interactive Web Development

Lecture 3: Forms and Client-Side Validation


This Lecture
• Overview of Forms

• Form Elements
– Text Fields, Password Fields, Text Areas WARNING!
– Drop-Down Lists, Radio Buttons and Checkboxes
This lecture contains a lot of content.
– Hidden Fields and Buttons
– Default Values, Labels, Fieldsets, Good Form Design You are not expected to memorise it.

The lecture is to introduce concepts


• Form Declaration and serve as a reference.
– GET and POST Methods Your familiarity with these concepts
will grow as you apply them.
• Form Validation
– Client-Side Validation in JavaScript

2
Overview of Forms
Overview of Forms
• Forms in web pages allow the user to
input data to be sent to the web server

• They consist of various form elements,


allowing for different types of input
– Text fields, drop-down lists, radio buttons…

• When a form is submitted, the data in its


elements is sent to the web server as
part of a request for a file (typically, a PHP
file that will process the data in some way)

4
Overview of Forms
• Forms are created using HTML

• Tags such as <input>, <textarea> and


<select> used to create form elements

• All elements of a form must be enclosed


in a <form> tag, defining them as a form
– This is also where overarching details are
specified, like which page to request upon
submitting and how to attach the data

• A single page can have multiple forms,


each inside their own <form> tag
– The page may also have other content…
5
Form Elements
Form Elements
• There are many form elements available, although the most common are:
– Text fields, password fields and text areas
– Drop-down lists
– Radio buttons and checkboxes
– Hidden fields
– Buttons

Exactly how they look differs slightly between browsers,


or even between different versions of the same browser!
7
Form Elements
• Most form elements are created using the <input> tag and the “type” attribute,
e.g. <input type="text" />, <input type="radio" />, <input type="submit" />
– Other tags are used for some elements, e.g. <textarea> and <select>

• Every form element (and the form itself) should be named using the “name”
attribute, to facilitate referring to it during form validation and processing
– You will refer to form/element names a lot in HTML, JavaScript and PHP, so make
them clear, logical and consistent, and remember that they are case-sensitive

• Use CSS to control how an element looks, such as size, colour, border, margin…
– This can be achieved using the “style” attribute e.g. style="width: 600px;"

8
Text Fields
• Created with the <input type="text" /> tag
• Designed to capture a string (any characters – letters, numbers, punctuation, etc)

• The “maxlength” attribute can control how many characters are accepted
– This is easily circumvented on the client-side – remember to enforce it server-side!

• The “placeholder” attribute places informative text in the box that disappears
when you start typing into it, reducing the need for text next to the field
– The “title” attribute can be used to specify “tooltip text” (can be done on all elements)

9
Password Fields
• Created with the <input type="password" /> tag
• Exactly the same as a text field, but it masks user input
– Supports the “maxlength” and “placeholder” attributes

• When setting a password (e.g. a registration form), always include a password


confirmation field to ensure that the user has not misspelt their password!

• The content of the field is still stored and transmitted in plain-text


– It is only hidden from the user, to prevent someone seeing it as you type it
– Hence, never use the GET method (more on this later) for a form if it contains a
password field, as it will be visible in the URL

10
Text Areas
• Created with the <textarea> tag
• Text areas allow for multiple lines of text – good for forum posts, descriptions…
– Unlike the <input> tag, there are separate opening and closing tags for <textarea>

• Supports the “maxlength” and “placeholder” attributes

• Set the initial size using “width” and “height” CSS properties
– Most browsers allow you to resize them as desired by dragging the lower right corner

11
Drop-Down Lists
• Created with the <select> and <option> tags
• Allows the user to select one option from a list
• Each option consists of a value and some text – the text is displayed to the user,
and the value is what gets submitted for processing
– The options are often drawn from a “lookup table” in the database (see Lecture 2)

• The first option is often instructional – e.g. “Select a category”


– Its value is usually empty or a character that can easily be detected during validation,
and it can be given the “disabled” attribute to prevent it from being selected

12
Radio Buttons
• Created with two or more <input type="radio" /> tags
• Allows the user to select one option from a list – much like a drop-down list

• Give multiple <input type="radio" /> tags the same name to make them a group
– Only one radio button in the group can be selected at a time
– Only the value of the selected button (if any) is submitted

• Ensure that the spacing of buttons makes button-to-text associations clear


– Use the <label> tag to allow the user to click the text itself (more on this later)

14
Checkboxes (Single)
• Created with one or more <input type="checkbox" /> tags
• Two main use cases:
– Single checkbox allowing for a yes/no input (e.g. “remember me” or “agree to terms”)
– Group of checkboxes allowing the user to select zero or more options from a list

• When using a single checkbox, a value is not needed – it is either checked or not
– The element will only be included in the submitted form data if the box was checked
– The existence of the element in your submitted form data tells you it was checked

Form data:

15
Checkboxes (Group)
• Created with one or more <input type="checkbox" /> tags
• Two main use cases:
– Single checkbox allowing for a yes/no input (e.g. “remember me” or “agree to terms”)
– Group of checkboxes allowing the user to select zero or more options from a list

• A group of checkboxes can be created by giving them all the same name,
making sure it ends with “[]” to submit the checked values as an array
– If none of the boxes are checked, the element won’t exist in the submitted form data
– If any of the boxes are checked, the form data will contain an array of their values

16
Hidden Fields
• Created with the <input type="hidden" /> tag
• Hidden fields are not visible to the user – they do not appear on the screen,
and users are not able to directly change the value
– Hidden fields are used to store values that are necessary or related to the form,
but that you do not want the user to see or directly control

• The value is usually set when the form is generated (via PHP), changed using
JavaScript, or hard-coded. Its value is submitted like any other element
– Do not use them for security – it is easy to see and change the value on client-side!

• Commonly used in “edit” forms to contain the database PK value of the row being
edited, since this information is needed, but not relevant to the user
17
Buttons (Submit and Reset)
• Created with the <input type="submit" /> and <input type="reset" /> tags
• When clicked, a submit button submits the form by attaching the current form
data to a request for the page specified in the “action” attribute of the <form> tag
– Client-side validation should occur here, potentially stopping the submission

• A reset button resets all elements in that form to their default values
– Should only be included where appropriate, since it is often not needed/annoying

• The “value” attribute determines the text shown on button


– This is also the value that will be submitted in the form data, but it is rarely relevant

18
Buttons (Generic)
• While “submit” and “reset” button have specific behaviours, you can also create
buttons that will do whatever you want – typically running some JavaScript code
– Created with the <input type=“button" /> tag

• The “onclick” event attribute allows you to specify what it should do when clicked
– This is typically a line of JavaScript code, or a call to a JavaScript function

Go one page back


(like pressing Back button)

Call a previously defined JavaScript Go to “index.php”


function named showHelp() (works like a link)

19
Default Values
• Most form elements can be given a default value. This is appropriate when
there is a likely or common selection, or to show current data in an “edit” form
– Use default values wisely (only when helpful and appropriate)

• Default values are specified differently for different fields:


– Text, Password and Hidden Fields: “value” attribute of the <input> tag
– Text Areas: Text between the opening and closing <textarea> tags
– Drop-Down Lists: “selected” attribute of the <option> tag
– Radio Buttons/Checkboxes: “checked” attribute of the <input> tag

20
Labels
• The <label> tag allows you to link text with form elements, so that clicking the text
is the same as clicking on the form element itself
– This makes clicking radio buttons and checkboxes much easier

• Simply wrap the <label> tag around the corresponding text and the form element:

21
Fieldsets
• The <fieldset> and <legend> tags let you visually group and name form elements
– You can disable all form elements in a fieldset by giving it the “disabled” attribute

23
Good Form Design
• Lay out and present your forms in a clean and logical way
– Arrange and size form elements to avoid a jagged look
– Group related elements and place them into fieldsets
– Make good use of space; elements can be side-by-side
(“tabindex” attribute sets the order they’re tabbed through)

• Use radio buttons when there are fewer and less-predictable options, and use a
drop-down list when there are a lot of predictable options or a strong default

• Use labels and placeholder text to increase the usability and clarity of your forms

• Inform the user of required fields and necessary formatting, and validate them

• Use consistent names between form elements and database columns


24
Form Declaration
Form Declaration (the <form> tag)
• The elements of a form should be enclosed in a <form> tag – the opening tag
goes before the first element, and the closing tag goes after the last element

• The form tag supports some important attributes:


– The “name” attribute will facilitate referring to the form in JavaScript (and CSS)

– The “method” attribute specifies the way in which the form data will be attached to the
request for the page/file specified in the “action” attribute when the form is submitted

– The “action” attribute specifies the file/page that will be requested when the form is
submitted – such a file/page is sometimes referred to as a “form handler”

– The “onsubmit” event attribute allows us to run JavaScript when the form is submitted
• The JavaScript can determine whether or not the form submission will proceed

26
The GET Method
• The method determines which HTTP method is used to request the page named
in the “action” attribute, changing how form data is attached to the request

• GET method:
– Form data is appended to the end of the requested URL, referred to as “URL data”
– Can be seen by users, and can have difficulty with special characters
– The URL can be bookmarked, and going to it will “re-submit the form” each time

• GET can be used when the request retrieves data and has no lasting effects, e.g.
a search or viewing something, and the form does not contain any sensitive data
– Only use GET when repeatedly submitting the form doesn’t cause any problems
– Never use GET for a form that is creating or editing things, involves passwords, etc.

27
The POST Method
• The method determines which HTTP method is used to request the page named
in the “action” attribute, changing how form data is attached to the request

• POST method:
– Form data is included in the body of the request itself
– Not visible to users in the URL, better at handling special characters and lots of data
– Cannot be bookmarked, and refreshing the page will ask you to confirm resubmission

• POST should be used for forms that have lasting effects, e.g. creating or editing,
purchasing, posting, etc., as well as any forms that contain sensitive data

POST /login.php HTTP/1.1 Example HTTP POST Request (Partial)

Request headers
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
...
Request body uname=jbloggs&pword=swordfish&token=6R14dU7d3
(form data)
28
GET and POST Methods
• Example URLs with form data (GET method):
– search_results.php?search_term=cats&exclude=dogs&safe_search=on&type=image

– login.php?uname=jbloggs&pword=swordfish&remember=on&token=6R14dU7d3

• Resubmission confirmation prompt (POST method):

29
URL Data in Links
• It is important to note that “URL data” can be added to the end of any URL
– Don’t need a form to exist or be submitted – can generate links with URL data in them
– This is a common way of passing a value to a page to view a specific piece of content
Database Table
thread_id username title content post_date
1045 ssmith Has anybody ever… Sometimes I like… 2019-03-
01...
Thread list page generated by 1046 jbloggs The latest version of… I think it has gone… 2019-03-
View thread page uses ID to
selecting data from database 01... select data for that thread
1047 ssmith What always makes… My friend does it… 2019-03-
02...

Thread List Page1048 ssmith Weird habits that you… This is gross, but… 2019-03- View Thread Page
02...
Links to view thread page
exampleforum.com/list_threads.php
contain URL data of thread ID exampleforum.com/view_thread.php?id=1045
exampleforum.com/view_thread.php?id=1046

view_thread.php?id=1045
view_thread.php?id=1046

(same page, different ID)

30
The “action” Attribute
• The “action” attribute specifies the file/page that will be requested when the form
is submitted – such a file/page is sometimes referred to as a “form handler”
– How the form data is attached to the request depends upon the “method” attribute

• A page containing a form can submit to itself, with the form processing PHP code
on the page written so that it only runs when the request contains form data
– A form processing page may redirect to another page after processing the form data
– All form handling pages should check that form data exists before trying to process it

• You can include URL data in the page specified in the “action” attribute

– This can be a handy trick when processing certain forms, as long as they use POST (if
they use GET, any URL data in the “action” will be overwritten by the form data)
– A hidden field or a session variable (covered later) can also achieve similar results

31
The “onsubmit” Event Attribute
• The “onsubmit” event attribute is triggered when the user tries to submit the form
– e.g. By clicking a submit button, or pressing Enter while focused on some field types

• If the event returns false, submission of the form is cancelled (remain on page)
– Otherwise, the submission proceeds (requests the page specified in “action” attribute)

• Typically used to call a JavaScript function that will perform validation of the form
– i.e. Checking that all of the form elements have been filled in correctly
– The function will return false if validation fails, and true (or nothing) if it succeeds

false Submission cancelled!

true Submission proceeds!


(anything else)
32
Form Validation
Form Validation
• Validation is the act of checking that the data provided by the user is valid
– Valid is not the same as correct: You can check that a field contains characters that
form a valid date in the expected date format, but not that it is actually a person’s DoB

• Validation can be performed on the client-side or the server-side:


– Client-side validation is more convenient to the user, but is easily circumvented
– Server-side validation is more robust and reliable (i.e. “secure”), but less convenient
– A combination of the two is ideal, although this obviously takes the most work
– In this module we will cover client-side validation

• All form data that interacts with your database should also be “sanitised”, to
ensure that characters that can mess up SQL commands are correctly handled
– This will be covered in a later module

34
Client-Side Validation
• Client-side validation is usually implement in JavaScript or HTML, both of which
are languages that are run in/by your browser – hence, client-side
– Usually occurs when the form is submitted, but can also be done field-by-field
– Can validate the content/range/format of fields, but cannot access the database

• Convenient, since validation to occur before the form data is sent to the server
– Can use JavaScript and CSS to alert the user to errors, highlight specific fields, etc.
– No delay of sending request and receiving response (especially if uploading large file)
• The form remains filled in, since the page isn’t re-loaded (server-side validation may need
extra effort to re-populate the form elements upon re-loading the form if validation fails)

• Client-side validation is easy to circumvent: HTML can be modified in the


browser, JavaScript can be disabled, form elements can be manipulated…
– Hence, use client-side validation for convenience, but not rely on it for security/safety
35
Client-Side Validation Example
• Let’s go through an example of a form that calls a JavaScript form validation
function when it is submitted:
– The function will check the content of the form elements for various criteria
– If an error is found, the function returns false and submission is cancelled

• The function is defined in a <script> tag in the <head> section of the HTML
– Can also be defined in a separate JavaScript file and “imported” using a <script> tag
<html> <html>
<head> <head>
<script> <script src="validation.js"></script>
function validateForm() { … } </head>
</script> <body>
</head> <form … onsubmit="return validateForm()">
<body> …
<form … onsubmit="return validateForm()"> </form>
… </body> validation.js
</form> </html> function validateForm() {
</body> …
</html> }

36
Client-Side Validation Example
ilable
ava ite!
• Here is the form we will validate: ode nit s
C nu
o

• This is the criteria we will check:


– Username is not blank
– Password is at least 6 characters
– Password matches confirmation
– A user type has been selected
– The postcode is a 4 digit number
– An access duration has been selected
– The “I agree” checkbox is checked

• If any of the criteria is not met, a message is shown and submission is cancelled
– If all of the criteria is met, the submission proceeds
37
JavaScript Form Validation
• First we’ll define the function and create a variable to refer to the form:

“document.create_form” refers to something


named “create_form” in the HTML document.

In this case, our form!


• JavaScript notes:
– Comments start with “//” and appear in green – Semicolon at end of statement
– Uses parentheses and curly brackets rather than colons and indentation
• JavaScript: • Python:
if (<boolean expression>) { if <boolean expression>:
<code to run if true> <code to run if true>
}
38
JavaScript Form Validation – Empty Text Field
• Each check involves an “if” statement that shows a message and returns false:

• Since “form” refers to the entire form, “form.uname” refers to something named
“uname” inside the form… The username field:
– Without the “form” variable it would be “document.create_form.uname” – clunky!
– “.value” refers to the value of the text field – i.e. what is currently typed into it

• If the value of the username text field is equal to an empty string, it is empty!
– Error found! Display message and return false to cancel the submission
– The “alert()” function displays an alert message box in the browser window

39
JavaScript Form Validation – Field Length

• “form.pword.value” refers to the value of the password field…

• “.length” refers to the length of that value (i.e. how many characters it
contains)
Referring to things in this way is known as “dot notation”, and it allows you to
refer to a specific thing by narrowing your focus down bit by bit, e.g.

“document.create_form.pword.value.length” refers to the length of the


value of the field named pword in the form named create_form in the document!

40
JavaScript Form Validation – Field Mismatch

• Check if value of password and password confirmation fields are not equal

41
JavaScript Form Validation – Radio Button Selected

• Since each radio button in a group has the same name, “form.utype” refers to
the radio button group rather than a single element

• “.value” refers to the value of the currently selected button in the group, e.g. “G”
– If none of the buttons in the group have been selected, “.value” is an empty string
• Hence, we can check if a selection has been made by checking for an empty string

42
JavaScript Form Validation – Numeric Value

• The “isNaN()” function returns true if the value passed to it is Not a Number

• “||” means “or”, allowing us to check multiple conditions at once


– We’ve already covered checking the length of a field

• Checks if the postcode value is not a number, or is not 4 characters long


– If either condition is true, the message is shown and the function returns false
– A “regular expression” can check this more accurately – see slide notes for details!

43
JavaScript Form Validation – Drop-Down Option Selected

• The value of a drop-down list is the value of the currently selected option

• We gave the placeholder an empty value, so we check for that to validate it

44
JavaScript Form Validation – Checkbox Checked

Closing the function body, i.e., what we started with “function validateForm() {”
• The “.checked” property of a checkbox is true if it has been checked

• “!” means “not”, resulting in a condition of “If the checkbox is not checked”

This is the final criteria that needs to be checked – the function ends at this point
without returning a value, allowing the submission to proceed!
45
Conclusion
• Forms are made up of various different elements
– Most use the <input> tag, but <textarea> and <select> are also used

• Default values, labels and fieldsets can increase the clarity and usability of forms

• When a form is submitted, a request is sent to a form handling page


– The GET and POST methods attach the form data to the request in different ways

• Form validation ensures that the form data is valid


– JavaScript can be used to validate forms on the client side, which is convenient for the
user but can easily be circumvented so should not be relied upon for safety/security

46
Readings and Research
• This week’s content is primarily focused upon HTML forms and JavaScript form
validation, which are outside the scope of the textbook

• The following resources cover these topics:


– Web forms (Mozilla Developer Network)
• Your first form
• Client-side form validation

– HTML Forms (w3schools)


• JavaScript Form Validation

– HTML Forms (tutorialspoint)


• JavaScript – Form Validation

47

You might also like