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

Javascript Forms Part III

The document discusses various HTML form elements and attributes for form validation using JavaScript regular expressions. It describes text fields, checkboxes, radio buttons, text areas, selection forms, submit buttons, and password entry. It also covers creating JavaScript functions to validate form data on submit and using regular expressions to perform validation checks on string patterns.

Uploaded by

Brandon Stark
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Javascript Forms Part III

The document discusses various HTML form elements and attributes for form validation using JavaScript regular expressions. It describes text fields, checkboxes, radio buttons, text areas, selection forms, submit buttons, and password entry. It also covers creating JavaScript functions to validate form data on submit and using regular expressions to perform validation checks on string patterns.

Uploaded by

Brandon Stark
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Advanced JavaScript

Develop And Design

FORM VALIDATION
Working with Forms
Handling Forms Recap
• Add submit handler to form itself
• Always have a submit button
• Always use valid action attribute
• HTML5 supports browser-based form
validation
JavaScript – Validate Forms Data

• Validate Forms Data


‒ Client-side JavaScript used to validate form
‒ Saves server resources and time
‒ Can Not Trust any data submitted to server
Hackers can quite easily simulate your web forms
and submit any data of their choosing.
Text Fields

• Small rectangular fields that allow a user to input text, submitting


it to the appropriate web server

• Commonly seen in search boxes


Text Fields
States width of
• Three attributes of interest text-field
States maximum
<input type="text"
characters allowed
size=“10"
maxlength="5"
value=“some text to overwrite" />

Gives default text


to appear in the
text-field
Checkboxes
• Checkboxes are useful for obtaining yes/no decisions from
users
Checkboxes

• There are two attributes of interest

<p> Pay way more than you should for luggage?


<input type="checkbox" Gives default answer
checked=“yes" “yes”
name=“options" /> </p>

Provides an ID by
which the field can
be referred
Radio Buttons

• Radio buttons allow a to choose only one of a selection of options


Radio Buttons
• There are two attributes of interest States the value that
will be submitted if
<p> Do you have any allergies? <br/> checked
Nuts: <input type="radio" value = “nuts” name=“allergies" />
Cheese: <input type="radio" value = “cheese” name=“allergies" />
Cat hair: <input type="radio" value = “cats” name=“allergies" />
</p>

Provides an ID which tells


which group of radio buttons
the field belongs to
Text Areas
• Text-areas allow the input of large chunks of text from the user

• Often used in blogs, etc,


or as a prompt for unusual
requests

• Specific <textarea> tag


used for each individual
text-area
Text Areas
• Five attributes are of interest States width of
the text-area
States height
of the text-area
<textarea cols="20" rows="5" wrap="hard“
disabled = “no” readonly = “no”> Ensures that the text is
Default text goes in here… ‘wrapped’ within the
</textarea> boundaries of the text-area.
Can be “hard”, “soft” or “off”.

States that text within


the text-area is ‘greyed States that text
out’ cannot be modified
within the text-area
Selection Forms and Drop-
Down Lists
• Selection Forms are usually used when >1 option may be
selected, whilst Drop-Down Lists are common when only one
choice is possible

• Syntax is similar to ordinary


HTML lists, with each list item
enclosed within tags within
the greater list tag

<select>
<option>text here</option>
<option>other text here</option>
</select>
Selection Forms and Drop-Down Lists
• There are three attributes of interest

States whether >1


option can be selected
<select size=“5" multiple=“yes"> (doesn’t work with drop-
<option>Cork</option> down lists)
<option>Kerry</option>
<option selected = “yes”>Waterford</option>
</select>

States how many options States whether any


are displayed (1 or less option is selected by
results in a drop down default
box, >1 results in a
selection form)
Submit Buttons
• When the user clicks on the "Submit" button, the content of the
form is sent to the server

<input type="submit" value="Submit these details" />

This specifies the text


to appear on the
button

• A submit button must be inside a <form> element to do anything


at all
Password Entry
• Password buttons are identical to regular text-fields, except the
text you are typing is replaced with stars, dots, etc, in the
browser window (so your password can’t be read over your
shoulder).

• <input> attribute ‘type’ must = “password”

<input type="password" size="5" maxlength="5" />

• This does not mean your password is encrypted, or changed at


all – it just ensures it is not visible to physical onlookers
Reset Buttons

• Reset buttons are simply buttons which restore the input fields
on your form to their default setting

• <input> attribute ‘type’ must = “reset”

<input type="reset" value="Reset fields?" />


HTML Form – Form Tag
1. <form> form elements </form>
2. Inside <form> tag
– method attribute specifies way in which data is
to be sent
• method="get" (limited data amount) method="post"

– action attribute specifies URL to which user data is to be


sent
<form method="post" action="formdata.php">
3. label and form element
<form method="post" action="mailto:youremailaddress">
<label>First Name: </label>
<input type="text" name="firstname" />
</form>
HTML Form – Form Elements and Organization
• Form Elements
Text Field <input type="text" name="firstname" />
Text Area <textarea rows="10" cols="30" name="texta">text</textarea>
Password <input type="password" name= "password" />
Radio Button <input type="radio" name= "y_n" value="yes" />Yes<br />
Checkbox <input type="checkbox" name="vehicle" value="Bike" />
Menu <select name="cars"><option value="kia">Kia</option></select>
Submit Button <input type="submit" value="Submit" />
Reset Button <input type=“reset" value="Submit" />
name needed to reference input element
• Organize Form Elements
<fieldset id="idname"><legend align=“left”>Legend Text</legend>Form
Elements</fieldset>
HTML5 Form – New Elements & Attributes
• HTML5 New Form Elements
Email Input <input type="email" name="email" />
Telephone Input <input type="tel" name="phone" />
URL Input <input type="url" name="website" />
Search Input <input type="search" name="search" />

• Attributes
required user needs to complete field for form to be able to submit
not supported in Internet Explorer 9- or in Safari

novalidate turns off HTML5 automatic validation via form element


pattern defines text pattern needed for form to be able to submit
placeholder provides hint of pattern needed for form to submit
JavaScript – Validate Forms Data: Create Functions
/* Need to validate contents of fields to make user have entered the right data.
Make use of Document Object Model and use JavaScript to access it */
function validate(form) {
fail = validateFirstname (form.firstname.value)
fail += validateLastname (form.lastname.value)
if (fail == "") return true
else { alert(fail); return false }
}

On Submit needs to trigger validate function


<form method="post" action="mailto:youremailaddress"
onSubmit="return validate(this)">
where this = current form
Form Validation with JavaScript

• We can use JavaScript to catch a certain amount of bad input


from users. These checks include:
– If text input is empty
– If text input is all numbers
– If text input is all letters
– If text input is alphanumeric
– If text input has the correct number of characters
– If a selection has been made from a drop down selector
– If an email address is valid
Regular expressions

• We perform many of these validation checks on the basis of


regular expressions
– A regular expression is an object that describes a pattern of
characters.
– Regular expressions are used to perform pattern-matching
and "search-and-replace" functions on text.
Regular Expressions
• A way to test strings against patterns.
• Complicated!
• Represented by RegExp objects.
Creating RegExp

var regexp = /pattern/;

var regexp = /pattern/modifier;


Regex Functions
• test()
• exec()
• search()
• match()
Metacharacters
Character Meaning
\ Escape
^ Indicates the beginning of the string
$ Indicates the end of the string
. Any single character except newline
| Alternatives (or)
[ Start of a class
] End of a class
( Start of a subpattern
) End of a subpattern
{ Start of a quantifier
} End of a quantifer
Quantifiers
Characte Meaning
r
? 0 or 1
* 0 or more
+ 1 or more
{x} Exactly x occurrences
{x,y} Between x and y (inclusive)
{x,} At least x occurrences
Character Classes
Class Shortcu Meaning
t
[0-9] \d Any digit
[\f\r\t\n\v] \s Any white space
[A-Za-z0-9] \w Any word character
[^0-9] \D Not a digit
[^\f\r\t\n\v] \S Not white space
[^A-Za-z0-9] \W Not a word character
Function to Test if Field is Empty

/* If field value is empty, return text. If field is not empty, return empty string
// use errorString as function parameterso that we can use same function for any
field */
function fieldEmpty (fieldvalue, errorString) {
if (fieldvalue == "") {
return (errorString);
} else {
return ""; // return empty string
}
}
Ensuring Forms are Not Blank
<html>
<head>
<script type='text/javascript'>
function leftBlank(formElement, warning){
if(formElement.value.length == 0){
alert(warning);
}
}
</script>
</head>
<body> <form>
<input type='text' id='customer name'/>
<input type='button'
onclick="leftBlank(document.getElementById('customer name'), 'Enter name')"
value='Check Field' />
</form> </body> </html>
Function to Test if Radio Button is Selected

function radioButtonSelected (radioButtons, errorString) {


radioSelected = -1;
for (i=radioButtons.length-1; i > -1; i--) {
if (radioButtons[i].checked) {
radioSelected = i;
i = -1; // set index to -1 so that for loop stops
}
}
if (radioSelected == -1) {
return (errorString);
} else {
return "";
}
}
Function to Count the Number of Checkboxes
Selected
function checkboxesSelected (checkboxes, errorString) {
var checkboxesSelected = 0;
for (i=0; i<checkboxes.length; i++) {
// test if current checkbox is checked ... if yes, add 1 to counter
if (checkboxes[i].checked) {
checkboxesSelected += 1; Have to Use
var checkboxesSelected = 0;
}
because:
} 1) function is also called
"checkboxesSelected" and without explicit
if (checkboxesSelected == 0) { var declaration, a name conflict is created.
return (errorString); 2) Good practice to have var when
declaring a variable …
} else {
return "";
} }
Ensuring a Selection is Made
<html>
<head>

<script type='text/javascript'>
function isSelection(elem, message){
if(elem.value == "Select a gender"){
alert(message);
}
}
</script>
</head>
<body> <form>

<select id='selection'>
<option>Select a gender</option>
<option>Male</option>
<option>Female</option>
</select>
<input type='button‘ onclick="isSelection(document.getElementById('selection'),
'Choose Male or Female')" value='Check Field' />
</form> </body> </html>
Restricting the Length of Input
<html>
<head>
<script type='text/javascript'>
function ensureLength(elem, min, max, message){
var userName = elem.value;
if(userName.length < min || userName.length > max){
alert(message);
}
}
</script>
</head>
<body>
<form> <input type='text' id='user name'/>
<input type='button'
onclick="ensureLength(document.getElementById('user name'), 4, 8, 'User name must be
between 4 and 8 characters')"
value='Enter a user name' />
</form>
</body>
</html>
Function to Test if Number is Within Certain
Range

function validateAge(fieldvalue) {
if (isNaN(fieldvalue)) return "No Age was entered.\n"
else if (fieldvalue < 18 || fieldvalue > 110)
return "Age must be between 18 and 110.\n"
return ""
}
Ensuring Input is Alphabetic
<html>
<head>
<script type='text/javascript'>
function isNumeric(elem, message){
var alphabeticExpression = /^[a-zA-Z]+$/;
/* This is a a regular expression /^[0-9]+$/ that will only match if the
string is all letters and is at least one character long */
if(!elem.value.match(alphabeticExpression )){
alert(message);
}
}
</script>
</head>
<body> <form> <input type='text' id='country'/>
<input type='button'
onclick="isNumeric(document.getElementById('country'), 'Not a country')"
value='Enter the country of the shipping address' />

</form> </body> </html>


Ensuring Input is Numeric
<html>
<head>
<script type='text/javascript'>
function isNumeric(elem, message){
var numericExpression = /^[0-9]+$/;
/* This is a a regular expression /^[0-9]+$/ that will only match if the
string is all numbers and is at least one character long */
if(!elem.value.match(numericExpression)){
alert(message);
}
}
</script>
</head>
<body>
<form> <input type='text' id='credit card'/>

<input type='button'
onclick="isNumeric(document.getElementById('credit card'), 'Not valid card')"
value='Enter credit card number' />
</form> </body> </html>
Ensuring Input is Alphanumeric
<html>
<head>
<script type='text/javascript'>
function isAlphaNumeric(elem, message){
var alphaNumericExpression = /[0-9a-zA-Z]/;
/* This is a regular expression /[0-9a-zA-Z]/ that will only match if the
string contains either letters or numbers, and is at least one character long */
if(!elem.value.match(alphaNumericExpression )){
alert(message);
}
}
</script>
</head>
<body> <form> <input type='text' id='street'/>
<input type='button'
onclick="isAlphaNumeric(document.getElementById('street'), 'Include the street
name and number')“ value='Enter the street of the shipping address' />
</form> </body> </html>
Function to Test Email Address
function validateEmail (fieldvalue) {
if (fieldvalue == "") return "No Email was entered.\n"

else if (!((fieldvalue.indexOf(".") > 0)


&& // Boolean AND

(fieldvalue.indexOf("@") > 0))

|| // Boolean OR

/[^a-zA-Z0-9.@_-]/.test(fieldvalue)

)
return "The Email address is invalid.\n"
return ""
}
Validating an Email Address
<html>
<head>
<script type='text/javascript'>
function emailValidator(elem, Message){
var emailExpression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
/* This expression checks to ensure the input follows the syntax of
[email protected]*/
if(!elem.value.match(emailExpression)){
alert(Message);
}
}
</script>
</head>
<body> <form> <input type='text' id='emailer'/>

<input type='button' onclick="emailValidator(document.getElementById('emailer'),


'Not a Valid Email Address')" value='Enter email address' />
</form>
</body>
</html>
Disabling the Submit Button

document.getElementById('submitButton').disabled = 'disabled';

OR

document.getElementById('submitButton').disabled = true;
Getting Values
var data = document.getElementById('comments').value;

var data = document.getElementById('selectMenu').value;

var data = document.getElementById('selectMenu').selectedIndex = 3;

for (var i = 0, count = elem.options.length; i < count; i++) {


// Use elem.options[i].selected/value/text
}
Linked Lists
Checkboxes and Radio
Buttons

var which = document.getElementById('someCheckbox').checked;

if (which.checked) {

var value = document.getElementById('someCheckbox').value;

}
Exercise

You might also like