CIT 415 Topic 8 Enhancing HTML Forms.pptx
CIT 415 Topic 8 Enhancing HTML Forms.pptx
1
Lecture Overview
2
JavaScript and Forms
• JavaScript is commonly used together with
forms for two reasons:
i. to add functionality that makes forms easier
for users to fill out
ii. to validate or process the data that a user
enters before that data is submitted to the
server.
3
Referencing Forms
1. Using getElementById() Method
• Example:
var myForm=getElementById(“frmReg”);
4
2. Using getElementsByTagName() Method
• Example:
var myForms = getElementsByTagName(“form”);
• By default, browsers create collections of a
few types of objects in an HTML document,
including: anchors, images, links, and forms.
5
3. Using the document Object's forms Property
• The property returns an array that holds
references to all the form objects on the page.
• Example:
var myForm = document.forms[0];
6
4. Using the this.form Property
• The this keyword in JavaScript always points
to the object that calls a given method.
• It is commonly used in eventhandler call.
• Example:
<input type="button" name="submit"
value="Save"
onclick="showElements(this.form)“ />
7
Form Properties
8
Form Methods
9
Form Events
10
The Form Elements Collection
• Refers to the set of all elements in a form.
• They collection is stored in an array in the
Form object.
• The elements in the collection are sorted as
they appear in the source code.
11
Referencing Form Elements
• Use the elements property of the forms object.
• Specify element index in order to reference
individual elements in the form.
• Example:
var myForm= document.getElementById("frmReg");
var myElement =myForm.elements [2];
– Refers to 3rd element in the 1st form in a web page.
12
• Browser view: Accessing form elements
13
• On clicking Submit button:
14
• Example: ex8-1FormElements.html
<!DOCTYPE html>
<html>
<head><title>Form Elements Access Demo</title></head>
<body>
<form id="frmReg">
<p>First name: <input type="text" id="fname" value=""></p>
<p>Last name: <input type="text" id="lname" value=""></p>
<p><input type="button" value="Submit" onClick="accessElement(this.form)" /></p>
</form>
<p id="p4"></p>
<p id="p5"></p>
<script>
function accessElement() {
var myForm= document.getElementById("frmReg");
var name1=myForm.elements[0].value;
var name2=myForm.elements[1].value;
document.getElementById("p4").innerHTML = "First name: " + name1;
document.getElementById("p5").innerHTML = "Second name: " + name2;
}
</script>
</body>
</html>
15
Common Form Elements Properties
• Most form controls are created by the <input>
tag, hence they share several properties and
methods.
1. The name Property
• The property sets or returns the name of an
element.
• Example
var x=myForm.elements [2].name;
16
2. The value Property
• Returns the value of the element.
• Example:
var
myForm=document.getElementById(“frmReg”);
var x =myForm.elements [2].value;
document.write(x)
17
3. The type Property
• Returns the type of element e.g. button, text,
checkbox etc.
• Example:
myForm=document.getElementById(“frmReg”);
var x =myForm.elements [2].type;
document.write(x);
18
Common Form Elements Methods
1. The focus() Method
• The method gives focus to an element.
• Example:
document.getElementById("fname").focus();
19
2. The blur() Method
• the method takes focus away from an
element.
• Example:
document.getElementById("fname").blur();
20
• Example: On clicking Focus button
Insertion pointer
appears blinking
21
• On clicking Blur button:
Insertion pointer
dissappears
22
• Example:ex-8-2FocusBlurMethods.html
<!DOCTYPE html>
<html>
<head><title>Focus Event Demo</title></head>
<body>
<p>Click Focus button or Blur button and observe insertion point move into text field or out</p>
<form>
First Name: <input type="text" id="fname" />
<p><input type="button" value="Focus" onclick="getFocus()" /> <input type="button"
value="Blur" onclick="loseFocus()" /></p>
</form>
<script>
function getFocus() {
document.getElementById("fname").focus();
}
function loseFocus() {
document.getElementById("fname").blur();
}
</script>
</body>
</html>
23
Common Form Elements Events
24
• Examples:
<input type="text" id="fname"
onfocus="getFocus()" onblur="loseFocus()"/>
25
• Example: On clicking inside the text field
26
• Example: On clicking outside the text field:
Text field no
background fill
27
• Example:ex8-3FocusBlurEvents.html
<!DOCTYPE html>
<html>
<head><title>Focus Events Demo</title></head>
<body>
<p>Click inside or outside the text field and observe color fill</p>
<form>
First Name: <input type="text" id="fname" onfocus="getFocus()" onblur="loseFocus()“ />
</form>
<script>
function getFocus() {
document.getElementById("fname").style.backgroundColor="red";
}
function loseFocus() {
document.getElementById("fname").style.backgroundColor="white";
}
</script>
</body>
</html>
28
Form Validation
• Validation - the process of checking that
information provided by users conforms to the
rules to ensure that it appropriately answers
the form’s questions and is provided in a
format that the site’s back-end programs can
work with.
• There are 2 types:
i. Browser-based validation
ii. Custom (User-defined) validation
29
Browser-Based Validation
• Modern browsers can perform some
validation.
• This is known as browser-based validation,
native validation, or HTML5 validation.
• HTML5 introduced some attributes that can
be used to specify various input constraints.
30
Specifying Browser-Based Validation
Parameters
1. Formnovalidate Attribute
• The formnovalidate attribute specifies that
the element should not be validated when
submitted.
• The attribute overrides the novalidate
attribute of the <form> element.
• It is used with the Submit button.
31
• Example:
<input type="submit" value="Submit"
formnovalidate="formnovalidate" />
32
2. max and min Attributes
• The max attribute specifies a control’s maximum
numerical value.
• The min attribute specifies a control’s minimum
numeric value.
• They are used with the number field.
• Used: the 2 are used to create a range.
• Example:
<input type="number" id="quantity"
min="1" max="5" title="Enter value -5" />
33
• Example: Entering value greater than 12
34
• On 2nd run: Entering value less than 1
35
• Example: ex8-4MinMax.html
<!DOCTYPE html>
<html>
<head><title>Focus Events Demo</title></head>
<body>
<p>Enter a value between 1 and 12</p>
<form>
Month: <input type="number" id="month" min="1"
max="12" />
</form>
</body>
</html>
36
3. maxlength
• The maxlength attribute specifies the maximum
number of characters allowed in the <input>
element.
• It is used with the text field and textarea
elements.
• Example:
<input type="password" id="username" n
ame="username" maxlength="10">
37
• Example: entering a value greater than
maximum length permitted
38
4. pattern
• The pattern attribute specifies a regular
expression that the <input> element's value is
checked against on form submission.
• The pattern attribute works with the following
input types: text, date, search, url, tel, email,
and password.
• N/B: Use the global title attribute to describe
the pattern to help the user.
39
• Example:
<input type="text" id="country“
pattern="[A-Za-z]{3}"
title="Three letter country code"/>
40
• Example: entering wrong email format
41
• Example: ex8-6Pattern.html
<!DOCTYPE html>
<html>
<head><title>Max Length</title></head>
<body>
<p>Enter a value maximun length 5 characters</p>
<form>
email: <input type="text" id="email" pattern="/^[\w\.\-
]+@[\w\.\-]+\.[a-zA-Z]+$/" title="use format:
[email protected]" />
</form>
</body>
</html>
42
5. required
• The attribute specifies that an input field must be
filled out before submitting the form.
• The attribute works with the following input
types: text, search, url, tel, email, password, date
pickers, number, checkbox, radio, and file.
• Example:
<input type="text" id="username"
required>
43
• Example: Submitting a form without filled out
a required field
44
Special type Attribute Values
• Additional browser-based validation is linked
to several values for the type attribute of the
input tag.
45
1. date, datetime, week, month, time,
datetime-local Attributes
• Specifies a date/time format.
• Example:
<input type="date" id=“date" />
46
2. email Attribute
• The email defines a field for an e-mail
address.
• The input value is automatically validated to
ensure it is a properly formatted e-mail
address.
• To define an e-mail field that allows multiple
e-mail addresses, add the "multiple"
attribute.
47
• Example: Entering invalid email format
48
3. number
• Specifies that input is numerical value.
• Example
<input type=“number” />
49
• Example: Browser Constraints
50
• Example: BrowserConstraints.html
<!DOCTYPE html>
<html>
<head>
<title>Validation Constraint Demo</title>
</head>
<body>
<h2>Subscription Details</h2>
<form>
User Name<input type="text" id="name" maxlength="12" required />
<br /><br />
Age:<input type="number" id="age" min="18" max="60" />
<br /><br />
DOB:<input type="date" id="dob" required />
<br /><br />
Email:<input type="email" id="email" required/>
<br /><br />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
</body>
</html>
51
Customizing Browser-Based
Validation Feedback
52
• Bubble appearance varies from one browser to
another.
• Also, it is not possible to set multiple validation
messages for a single field at once
• There need for custom validation may arise out of
the above 2 browser shortcomings.
• Browser-based validation feedback are
customizable through the properties and
methods of JavaScript constraint validation API.
53
JavaScript Form Validation API
Properties
1. validationMessage - Sets or returns the text
(message) to be displayed to the user after a
failed submit event if the field’s validity value is
false (failed).
54
2. validity - Returns a ValidityState object that
contains several properties describing the
validity state of the element.
• They include:
a) valid: Returns true if the element meets all
its validation constraints, or false if it fails any
constraint.
b) valueMissing: Returns true if the element
has no value, or false otherwise.
55
c). typeMismatch: The control value does not
conform to the rules for the type attribute value.
d). patternMismatch: Returns true if the value does
not match the specified pattern or false otherwise.
e) willValidate: Returns true if the element will be
validated when the form is submitted; false
otherwise.
f) tooLong: Returns true if the value is longer than
the maximum length specified by the maxlength
attribute.
56
g). tooShort: Returns true if the value is shorter
than the minimum length specified by the
minlength attribute.
h) rangeOverflow: Returns true if the value is
greater than the maximum specified by the
max attribute.
i) rangeUnderflow: Returns true if the value is
less than the minimum specified by the min
attribute.
57
Javascript validity Object methods
1. checkValidity() : Returns true for a control if
the control value is valid
2. setCustomValidity(): Sets custom validation
message and rules.
3. reportValidity(): Reports invalid field(s) using
events.
• Its useful in combination with
preventDefault() method in an onSubmit
event handler.
58
The preventDefault() Event Method
• The method disables default behavior of an event
when it fires.
• Syntax:
event.preventDefault();
• Example 1:
document.getElementById("myAnchor").addEventLi
stener("click", function(event)
{event.preventDefault() });
59
The Process of Validating Submitted
Data
• When a submit button is clicked, the submit
event fires.
• To customize validation feedback:
Step 1: stop the browser from perform native
validation on the form.
Example:
<form id="frmReg" novalidate="novalidate">
60
Step 2:Stop the form from being submitted.
• use the preventDefault() event method.
• Example:
event.preventDefault();
Step 3: specify the validation required.
• Example:
fname.validity.valueMissing ➔ returns T/F
age.validity.rangeUnderflow ➔ returns T/F
61
Step 4: set a new custom validation feedback
message using the setCustomValidity() method.
• Example:
fname.setCustomValidity("Field cannot be
empty.");
• N/B: since default events in the form are off,
switch on the feedback bubble using the
reportValidity() method.
62
• Example:
if (fname.validity.valueMissing) {
fname.reportValidity();
fname.setCustomValidity("Field cannot be
empty.");
}
Step 5: submit the form manually using the
submit() method of the form object.
Example:
myForm.submit();
63
• Example:CustomMessage.html
<!DOCTYPE html>
<html>
<head>
<title>Elements Validation Demo</title>
<script>
function inputValidation(evt) {
evt.preventDefault(); // prevent form from submitting
var myForm=document.getElementById("frmReg");
var fname=myForm.elements[0];
fname.reportValidity();
if (fname.validity.valueMissing) {
fname.setCustomValidity("Field cannot be empty.");
}
}
</script>
</head>
<body>
<h2>Various Elements Validation</h2>
<form id="frmReg" novalidate="novalidate">
User Name<input type="text" id="fname" required />
<br /><br />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
<script>
var myForm = document.getElementsByTagName("form")[0];
myForm.addEventListener("submit", inputValidation);
</script>
</body>
</html>
64
Common Browser Validation
Parameters
1. Checking Missing Values
• Use the valid.valueMissing property.
• Example:
if (fname.validity.valueMissing) {
fname.reportValidity();
fname.setCustomValidity("Field cannot be
empty.");
}
65
2. Validating Out of Range Data
• Use either valid.rangeUnderflow or
valid.rangeOver properties.
• Example:
if (age.validity.rangeUnderflow) {
age.reportValidity();
age.setCustomValidity("Under age.");
}
66
3. Validating Special Input Type (e.g. email)
• Used in conjunction with the type attribute e.g
<input type=“email” />
• Use the validity.typeMismatch property.
• Example:
if (mail.validity.typeMismatch) {
mail.reportValidity();
mail.setCustomValidity("Invalid email.");
}
67
• Example: ex8-11CustomizedBrowserValidation.html
<!DOCTYPE html>
<html>
<head>
<title>Elements Validation Demo</title>
</head>
<body>
<h2>Various Elements Validation</h2>
<form id="frmreg" novalidate="novalidate">
User Name<input type="text" id="name" required />
<br /><br />
Email:<input type="email" id="email" required />
<br /><br />
Age:<input type="number" id="age" min="18" max="60" required />
<br /><br />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
68
<script>
var myForm = document.getElementById("frmreg");
myForm.addEventListener("submit", formValidation);
function formValidation(evt) {
evt.preventDefault(); // prevent form from submitting
var empName= document.getElementById("name");
var empEmail= document.getElementById("email");
var empAge= document.getElementById("age");
validateName(empName);
validateEmail(empEmail);
validateAge(empAge);
}
function validateName(name) {
if (name.validity.valueMissing) {
name.reportValidity();
name.setCustomValidity("Field cannot be empty!");
}
}
69
function validateEmail(mail) {
if (mail.validity.typeMismatch) {
mail.reportValidity();
mail.setCustomValidity("Invalid email!");
}
}
function validateAge(age) {
if (age.validity.rangeUnderflow) {
age.reportValidity();
age.setCustomValidity("Under age!");
}
if (age.validity.rangeOverflow) {
age.reportValidity();
age.setCustomValidity("Retirement age!");
}
}
</script>
</body>
</html>
70
Programming Custom Validation
• Common validation procedures include:
i. Checking that required fields contain entries
ii. Checking values dependent on other fields
iii. Checking for appropriate content type.
• To write custom validation, add the novalidate
attribute to the form element to disable
browser-based validation.
71
Validating Required Fields with
Custom Functions
• This involves retrieving the control and checking
if it is empty.
• Example:
var myForm=document.getElementById("frmReg");
var fname=myForm.elements[0];
if (fname.value == "") {
alert("Field cannot be empty.");
}
72
• For custom validation, it is helpful to use the try/catch structure.
• Example:
var myForm=document.getElementById("frmReg");
var fname=myForm.elements[0];
try {
if (fname.value == "") {
throw "message";
}
}
catch(message) {
alert("Field cannot be empty.");
}
73
• Example: CustomValidation.html
<!DOCTYPE html>
<html>
<head>
<title>Submit Custom Validation Demo</title>
<script>
function inputValidation(evt) {
evt.preventDefault(); // prevent form from submitting
var myForm=document.getElementById("frmReg");
var fname=myForm.elements[0];
try {
if (fname.value === "") {
throw "message";
}
}
catch(message) {
alert("Field cannot be empty.");
}
myForm.submit();
}
74
</script>
</head>
<body>
<h2>Subscription Details</h2>
<form id="frmReg" novalidate="novalidate">
User Name<input type="text" id="fname" required />
<br /><br />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
<script>
var myForm = document.getElementsByTagName("form")[0];
myForm.addEventListener("submit", inputValidation);
</script>
</body>
</html>
75