JavaScript is most often used in conjunction with HTML to perform client-side data validation. However, JavaScript also supplies the Dynamic portion of Dynamic HTML (DHTML), along with CSS and the HTML DOM.
Field validation
JavaScript can be used to validate data entered in an HTML form before the form is submitted to the server. Note that using JavaScript in this manner is strictly a usability enhancement of the form and should not be considered a security mechanism.
The following figure shows a simple HTML form that contains fields for user input.

A simple HTML form with fields for user input
If the EMail Address field on the form is a required field, JavaScript can be used to ensure the user enters a value in the field. The following code example shows the markup for the simple form shown in the previous figure. When the form is submitted, the validate_form() function is called in the onSubmit event of the form. The validate_form() function in turn calls the required_field() function, both of which are defined within the <head> of the page. In this example, validate_form() is only checking to make sure the EMail Address field is not empty. However the function could also be used to check the format of text entered in the Email Address field, as well as the values of other fields on the form.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>River Bend Coffee</title>
<script type="text/javascript">
function required_field(field, alerttext) {
with (field) {
if (value == null || value=="") {
alert(alerttext);return false;
} else {
return true
}
}
}
function validate_form(thisform) {
with (thisform) {
if(required_field(EMail, "E-mail is a required field.") == false) {
email.focus();
return false;
}
}
}
</script>
</head>
<body>
<form onsubmit="return validate_form(this)" action="#" method="post">
<img src="working/JavaScript+Primer_files/riverbend_logo.gif" height="120" width="120">
<p><label for="FirstName">First Name:</label> <input type="text" name="FirstName" id="FirstName" size="20"></p>
<p><label for="LastName">Last Name:</label> <input type="text" name="LastName" id="LastName" size="20"></p>
<p><label for="EMail">Email Address:</label> <input type="text" name="EMail" id="EMail" size="30"></p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Note that the validate_form() and required_field() functions are defined within the <head> of the page only so that the example can be contained in a single file. In practice, it is better to define all of your JavaScript functions in an externally linked file. See the JavaScript primer for more details on linked scripts.