JavaScript Form Validation and Announcements

 
CS 2033
Multimedia &
Communications II
 
LECTURE 8 – JAVASCRIPT FORM VALIDATION
 
1
 
Announcements
 
Quiz 2 will be posted on OWL this
Wednesday and Thursday.
It includes content from Lectures 5-7
It is linear and 1 submission only
 
Assignment 3 will be posted by the
end of this week.
 
2
 
JavaScript recap
 
Display messages
alert("Hi");
     
// Pop-up
document.write("Hi");
 
// Write to site
Variables
var a = "Hello";
   
// String
var b = 12;
     
// Integer
var c = 1.5;
    
// Float/Double
var d = false;
    
// Boolean
 
3
 
JavaScript recap
 
Arrays
var x = [4, 2, 1, 5];
alert(x[0]);
  
// Displays 4
x[3] = 9; 
  
// Changes the 5 to a 9
HTML element getters
getElementById(
id
)
getElementsByTagName(
tag
)
getElementsByClassName(
class
)
 
4
 
JavaScript recap
 
Changing CSS styles
mydiv.style.width = "200px";
mydiv.style.backgroundColor = "red";
Changing classes or ID
mydiv.className = "redbox title";
mydiv.id = "maintitle";
Changing content
mydiv.innerHTML = "New content";
 
5
 
JavaScript recap
 
Event listeners
onclick, 
ondblclick
onmouseover, onmouseout
onfocus, onblur
onchange
onkeypress, onkeydown, onkeyup
onscroll
onload
 
6
 
JavaScript recap
 
Event listeners
Inline (HTML)
<div id="x" onclick=" this.style.width =
'300px'"></div>
In JavaScript
var x = document.getElementById("x");
x.addEventListener("click", function() {
  
this.style.width = "300px" }
);
 
7
 
JavaScript recap
 
Conditionals
if (x < 10) {
  
alert("A");
} else if (x > 30) {
  
 alert("B");
} else {
  
 alert("C");
}
 
8
 
JavaScript recap
 
Functions
function calculate(x, y, z) {
  
var a = x - 2;
  
var b = y * z;
  
var result = (a+b) / (z-a)
  
return result;
}
calculate(5, 2, 4);
var q = calculate(2, 3, 2);
 
9
 
JavaScript recap
 
Loops
for (x = 0; x < 5; x++) {
  
document.write(x);
}
var array = [5, 9, 2, 7, 6];
for (x = 0; x < array.length; x++) {
  
document.write(array[x]);
}
 
10
 
Form validation
 
We previously saw how to create a
web form and style it with CSS.
We also used some HTML attributes
in a form: maxlength and required.
Now we can use JavaScript to
have much more control over the
form validation process.
Conditionals are important here!
 
11
 
Form validation
 
Form validation comes in a variety
of types and complexity levels.
Run validation as the user types or
selects data, or at the end when
they submit it, or a combination.
Add event listeners to run the
validation accordingly.
 
12
 
Form validation
 
For real-time validation:
Keyboard events: 
keypress
 / 
onkeyup
Blur (lose focus) event: 
onblur
 
For submission-time validation:
Button click event: 
onclick
 / 
onsubmit
 
13
 
Form validation
 
What are common criteria in the
validation process for text?
Textbox left blank
Valid text length – over minimum or
within a range
Type(s) of characters in text
Specific pattern (i.e. postal codes)
 
14
 
Form validation
 
What are common criteria in the
validation process for other inputs?
Radio / Dropdown list: was an
option selected? Is the selected
option valid?
Checkboxes: is there a limit/range
of how many should be selected?
 
15
 
Form validation
 
We won't go through every type of
validation. Some are far too
advanced for this course.
We'll focus on the commonly used
and simple types of validation.
The first step is to get the user's input
in the form as a variable. Then we
can examine it for validation.
 
16
 
Form validation
 
Access an input field normally: get
element(s) by ID/class/tag.
Then use dot notation to retrieve
the value of that element.
For text, password, and textarea,
use 
element
.value
For radio buttons and checkboxes,
use 
element
.checked
 
17
 
Form validation
 
For select dropdown menus, use
element
.selectedIndex to get the
array index and 
element
.options to
get the array of options.
var opts = dd.options;
var si = dd.selectedIndex;
var sel = opts[si];
alert(sel.index + ", " + sel.text);
 
18
 
Form validation
 
Checking if a textbox is left empty.
Compare the text to "" (quotation
marks with nothing in between)
if (
name == ""
) {
    // Empty.
} else {
    // Not empty.
}
 
19
 
Form validation
 
Checking if the entered text is long
enough (in characters).
Examine the number of characters in
the string variable using .length
if (
name.length < 5
) {
    // Too short.
} else {
    // Long enough.
}
 
20
 
Form validation
 
More specific criteria like character
types or patterns require that we
examine individual characters.
Loops are important to iterate over
a string or a list of items.
For these validation criteria, we can
loop over the input string and
check the characters at each slot.
 
21
 
Form validation
 
Checking the character types
within a string can be complex.
One basic option to check if the
entire string is a number or not is
with the built-in isNaN() function
(checks if value is Not a Number).
isNaN(34) = isNaN(2.5) = false
isNaN("abc") = isNaN("B7") = true
 
22
 
Form validation
 
Before we continue with the form
validation, let's look more at 
strings
.
Strings are just arrays of characters;
only one character can be placed
in each slot. Recall that positions
start at 0 from the leftmost slot.
var course = "CS2033";
var msg = "HELLO WORLD";
 
23
 
Form validation
 
Like other arrays, access each of
the characters with a for-loop.
var msg = "HELLO WORLD";
for (var i = 0; i < msg.length; i++) {
    // Examine character at position i
}
 
24
 
Form validation
 
Examining a character usually
means comparing it to another
value or a range of values.
One option is to get the value
directly from the string at position i
and use that value for the analysis.
var char = msg[i];
if (char == "W") {
}
 
25
 
Form validation
 
Instead of getting the character
value itself in the loop, you could
get its ASCII code for analysis.
var code = msg.charCodeAt(i);
if (code >= 65 && code <= 90) {
}
Look up ASCII code charts for the
ranges (65 to 90 is capital letters).
 
26
 
Form validation
 
When using loop-based analysis,
create a Boolean flag for "success".
Default value depends on situation.
Change its value to true or false as
needed in the loop.
At the end, check its final value to
see if the overall string is valid or
invalid.
 
27
 
Form validation
 
i.e check if text contains only letters
var success = true;
for (var i = 0; i < str.length; i++) {
  
if (isLetter(str[i] == false) {
   
success = false;
  
}
}
if (success == true) { … }
else { … }
 
28
 
Form validation
 
Some user input is complex and
difficult to analyze using these
simple approaches.
Another option is to use 
regular
expressions
 (regex).
Check if a user-typed string follows a
specific pattern or template.
 
29
 
Form validation
 
For example, consider an email
address.
Username/custom text
@ (at symbol)
Domain name
Extension (top level domain)
i.e. bsarlo@uwo.ca
 
30
 
Form validation
 
Patterns/templates are encoded
using specific characters/symbols.
For an email address, the regex is:
/.+@.+\..+/
Can you read this?
It won't be on the exam 
https://www.debuggex.com/cheat
sheet/regex/javascript
 
31
 
Form modifications
 
JavaScript is also used to 
modify
web forms dynamically.
What is meant by modifying forms?
Hiding/showing fields
Changing the set of available options
in a dropdown menu list
Automatically checking a series of
checkboxes.
 
32
 
Form modifications
 
Most of these modifications can be
done with the JavaScript features
you already know!
i.e. changing a class name or
individual styles, using conditionals,
loops, functions, etc.
 
33
 
Form modifications
 
A new method that helps with this is
the ability to create a new HTML
element directly in JS.
document.createElement(
type
);
Adding a new element to the
website is then done with
appendChild(
element
);
They can be added into a
container or to the body itself.
 
34
 
Form modifications
 
i.e. Add a new text input box into
the "con" container.
var x = document.createElement("input");
x.type = "text";
x.className = "contact";
x.id = "provinceBox";
var c = document.getElementById("con");
c.appendChild(x);
 
35
 
Form modifications
 
Let's code some examples of form
validation and modification…
 
http://www.csd.uwo.ca/~bsarlo/cs
2033b/samples/lec8/shells/
 
36
Slide Note
Embed
Share

This content covers JavaScript form validation, announcements about upcoming quizzes and assignments, and a JavaScript recap on arrays, CSS styles, event listeners, conditionals, and functions. It includes practical examples and explanations to enhance understanding of JavaScript programming.

  • JavaScript
  • Form Validation
  • Announcements
  • Arrays
  • CSS Styles

Uploaded on Mar 08, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. 1 CS 2033 Multimedia & Communications II LECTURE 8 JAVASCRIPT FORM VALIDATION

  2. Announcements 2 Quiz 2 will be posted on OWL this Wednesday and Thursday. It includes content from Lectures 5-7 It is linear and 1 submission only Assignment 3 will be posted by the end of this week.

  3. JavaScript recap 3 Display messages alert("Hi"); document.write("Hi"); // Write to site Variables var a = "Hello"; var b = 12; var c = 1.5; var d = false; // Pop-up // String // Integer // Float/Double // Boolean

  4. JavaScript recap 4 Arrays var x = [4, 2, 1, 5]; alert(x[0]); x[3] = 9; HTML element getters getElementById(id) getElementsByTagName(tag) getElementsByClassName(class) // Displays 4 // Changes the 5 to a 9

  5. JavaScript recap 5 Changing CSS styles mydiv.style.width = "200px"; mydiv.style.backgroundColor = "red"; Changing classes or ID mydiv.className = "redbox title"; mydiv.id = "maintitle"; Changing content mydiv.innerHTML = "New content";

  6. JavaScript recap 6 Event listeners onclick, ondblclick onmouseover, onmouseout onfocus, onblur onchange onkeypress, onkeydown, onkeyup onscroll onload

  7. JavaScript recap 7 Event listeners Inline (HTML) <div id="x" onclick=" this.style.width = '300px'"></div> In JavaScript var x = document.getElementById("x"); x.addEventListener("click", function() { this.style.width = "300px" } );

  8. JavaScript recap 8 Conditionals if (x < 10) { } else if (x > 30) { alert("B"); } else { alert("C"); } alert("A");

  9. JavaScript recap 9 Functions function calculate(x, y, z) { var a = x - 2; var b = y * z; var result = (a+b) / (z-a) return result; } calculate(5, 2, 4); var q = calculate(2, 3, 2);

  10. JavaScript recap 10 Loops for (x = 0; x < 5; x++) { document.write(x); } var array = [5, 9, 2, 7, 6]; for (x = 0; x < array.length; x++) { document.write(array[x]); }

  11. Form validation 11 We previously saw how to create a web form and style it with CSS. We also used some HTML attributes in a form: maxlength and required. Now we can use JavaScript to have much more control over the form validation process. Conditionals are important here!

  12. Form validation 12 Form validation comes in a variety of types and complexity levels. Run validation as the user types or selects data, or at the end when they submit it, or a combination. Add event listeners to run the validation accordingly.

  13. Form validation 13 For real-time validation: Keyboard events: keypress / onkeyup Blur (lose focus) event: onblur For submission-time validation: Button click event: onclick / onsubmit

  14. Form validation 14 What are common criteria in the validation process for text? Textbox left blank Valid text length over minimum or within a range Type(s) of characters in text Specific pattern (i.e. postal codes)

  15. Form validation 15 What are common criteria in the validation process for other inputs? Radio / Dropdown list: was an option selected? Is the selected option valid? Checkboxes: is there a limit/range of how many should be selected?

  16. Form validation 16 We won't go through every type of validation. Some are far too advanced for this course. We'll focus on the commonly used and simple types of validation. The first step is to get the user's input in the form as a variable. Then we can examine it for validation.

  17. Form validation 17 Access an input field normally: get element(s) by ID/class/tag. Then use dot notation to retrieve the value of that element. For text, password, and textarea, use element.value For radio buttons and checkboxes, use element.checked

  18. Form validation 18 For select dropdown menus, use element.selectedIndex to get the array index and element.options to get the array of options. var opts = dd.options; var si = dd.selectedIndex; var sel = opts[si]; alert(sel.index + ", " + sel.text);

  19. Form validation 19 Checking if a textbox is left empty. Compare the text to "" (quotation marks with nothing in between) if (name == "") { // Empty. } else { // Not empty. }

  20. Form validation 20 Checking if the entered text is long enough (in characters). Examine the number of characters in the string variable using .length if (name.length < 5) { // Too short. } else { // Long enough. }

  21. Form validation 21 More specific criteria like character types or patterns require that we examine individual characters. Loops are important to iterate over a string or a list of items. For these validation criteria, we can loop over the input string and check the characters at each slot.

  22. Form validation 22 Checking the character types within a string can be complex. One basic option to check if the entire string is a number or not is with the built-in isNaN() function (checks if value is Not a Number). isNaN(34) = isNaN(2.5) = false isNaN("abc") = isNaN("B7") = true

  23. Form validation 23 Before we continue with the form validation, let's look more at strings. Strings are just arrays of characters; only one character can be placed in each slot. Recall that positions start at 0 from the leftmost slot. var course = "CS2033"; var msg = "HELLO WORLD";

  24. Form validation 24 Like other arrays, access each of the characters with a for-loop. var msg = "HELLO WORLD"; for (var i = 0; i < msg.length; i++) { // Examine character at position i }

  25. Form validation 25 Examining a character usually means comparing it to another value or a range of values. One option is to get the value directly from the string at position i and use that value for the analysis. var char = msg[i]; if (char == "W") { }

  26. Form validation 26 Instead of getting the character value itself in the loop, you could get its ASCII code for analysis. var code = msg.charCodeAt(i); if (code >= 65 && code <= 90) { } Look up ASCII code charts for the ranges (65 to 90 is capital letters).

  27. Form validation 27 When using loop-based analysis, create a Boolean flag for "success". Default value depends on situation. Change its value to true or false as needed in the loop. At the end, check its final value to see if the overall string is valid or invalid.

  28. Form validation 28 i.e check if text contains only letters var success = true; for (var i = 0; i < str.length; i++) { if (isLetter(str[i] == false) { success = false; } } if (success == true) { } else { }

  29. Form validation 29 Some user input is complex and difficult to analyze using these simple approaches. Another option is to use regular expressions (regex). Check if a user-typed string follows a specific pattern or template.

  30. Form validation 30 For example, consider an email address. Username/custom text @ (at symbol) Domain name Extension (top level domain) i.e. bsarlo@uwo.ca

  31. Form validation 31 Patterns/templates are encoded using specific characters/symbols. For an email address, the regex is: /.+@.+\..+/ Can you read this? It won't be on the exam https://www.debuggex.com/cheat sheet/regex/javascript

  32. Form modifications 32 JavaScript is also used to modify web forms dynamically. What is meant by modifying forms? Hiding/showing fields Changing the set of available options in a dropdown menu list Automatically checking a series of checkboxes.

  33. Form modifications 33 Most of these modifications can be done with the JavaScript features you already know! i.e. changing a class name or individual styles, using conditionals, loops, functions, etc.

  34. Form modifications 34 A new method that helps with this is the ability to create a new HTML element directly in JS. document.createElement(type); Adding a new element to the website is then done with appendChild(element); They can be added into a container or to the body itself.

  35. Form modifications 35 i.e. Add a new text input box into the "con" container. var x = document.createElement("input"); x.type = "text"; x.className = "contact"; x.id = "provinceBox"; var c = document.getElementById("con"); c.appendChild(x);

  36. Form modifications 36 Let's code some examples of form validation and modification http://www.csd.uwo.ca/~bsarlo/cs 2033b/samples/lec8/shells/

Related


More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#