Share
Explore BrainMass

Using javascript to Validate Form Values

Modify Simple JavaScript with validation

lab5xx.htm

<html>
<head>
<script type="text/javascript">
<!--
function MyLoadFunction() {
alert("Welcome to my Lab 5!");
}
-->
</script>
</head>

<body background="background.png" onLoad="MyLoadFunction();">
<div align="center">
<h1>Name</h1>
<h2>Course</h2>
<h3>Lab</h3>
</div>
</body>
</html>

Step 1: Using a text or HTML editor modify your lab5xx.htm page (see above) and save it as lab6xx.htm.

Step 2: Add a link to an external JavaScript file called lab6xx.js

Step 3: Create the external JavaScript file. Ensure that all of your form fields have a unique name on the lab6xx.htm file.

Step 4: Verify on the submission of the form the following:
- Ensure that none of the fields are empty.
- Ensure that Name field does not contain numbers and special characters.
- Ensure that the email field contains a proper email address using a regular expression condition in an ?if?then? statement. Use the code below (HINT: copy and paste code into Notepad to strip it of all formatting values BEFORE pasting into your HTML editor):

if (/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/.test(YourForm.YourEmailField.value)){
return (true);
}else{
return(false);
}

Step 5: If the fields are empty return false to the browser and alert the user as to which fields are empty. If the email is incorrect, alert the user that they must correct the format of that particular field. However, if everything is correct you can return true to the browser and the form data will be sent to your professor?s email.

Step 6: Save the web page and the external script file in two different formats: First save them as text documents--as lab6xx.txt and lab6jsxx.txt. Second save them as lab6xx.htm and lab6xx.js.

Solution Preview

Solving this problem requires making adjustments to the HTML file that is provided and creating a new Javascript file that contains the validation function.

The first step is making adjustments to the HTML. To link to an external Javascript file, rather than having the Javascript in the head itself, the "src" attribute for the "script" tag is used:

<script src="lab6xx.js" language="javascript" type="text/javascript"></script>

Since the Javascript function needs to have form fields to operate on those fields need to be added to the HTML file. It is sufficient to ...

Solution Summary

This solution demonstrates how to use javascript to ensure that all form fields have a value. It also shows how to use pattern matching to make sure that email addresses are of the right form.

$2.19