Basics – Functions and Form Validation

Basics – Functions and Form Validation

Prerequisites

You should have knowledge of – or mastered the basic javascript material at Lecture – Basics – Javascript variables and scope and Lecture – Basics – Javascript Arrays

Summary

Topics covered:

1. Form Validation using Javascript

Video

http://www.youtube.com/watch?v=SPNLJBykUzc

Reference Materials

<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
<script type=”text/javascript”>
function ValidateForm()
{
var fname = document.forms[“inputForm”][“fname”].value;
if (!ValidateNotBlank(fname, “Name” ))  return false;var bday = document.forms[“inputForm”][“bday”].value;
if (!ValidateNotBlank(bday, “Date” ))  return false;

if (!ValidateDate()) return false;
return true;
}

function ValidateNotBlank(val, message)
{
if (val == null || val == “”)
{
alert(“Must enter a value for ” + message);
return false;
}
return true;
}

function ValidateDate()
{
var d = document.forms[“inputForm”][“bday”].value;
var d_as_date = Date.parse(d);
var today = new Date();

if (d_as_date > today)
{
alert(“The date entered is after today”);
return false;
}
return true;
}
</script>
</head>
<body>

<form name=”inputForm” onsubmit=”return ValidateForm();” method=”post” action=”mailto:eaglinr@daytonastate.edu” >
Input Full Name: <input type=”text” name=”fname” /><br/>
Input Date before today: <input type=”date” name=”bday” placeholder=”mm/dd/yyyy” /><br/>
<input type=”submit” value=”submit” />
</form>
</body>
</html>

Additional Information

COP 4813 Lectures