IWD Lecture 3 Forms and Client-Side Validation-2
IWD Lecture 3 Forms and Client-Side Validation-2
• 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.
2
Overview of Forms
Overview of Forms
• Forms in web pages allow the user to
input data to be sent to the web server
4
Overview of Forms
• Forms are created using HTML
• 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
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>
• 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)
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
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
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
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)
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
– 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
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
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
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
• 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)
• 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
• 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:
• 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
• “.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.
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
43
JavaScript Form Validation – Drop-Down Option Selected
• The value of a drop-down list is the value of the currently selected option
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
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
47