<h2>Test JavaScript Form Validation</h2>
<form id="theForm" method="get" action="submitData">
<table>
<tr>
<td>Name<span class="red">*</span></td>
<td><input type="text" id="name" name="name"/></td>
<td id="nameError" class="red"> </td></tr>
<tr>
<td>Address</td>
<td><input type="text" id="address" name="address" /></td>
<td id="addressError" class="red"> </td></tr>
<tr>
<td>Postcode<span class="red">*</span></td>
<td><input type="text" id="zipcode" name="zipcode" /></td>
<td id="zipcodeError" class="red"> </td></tr>
<tr>
<td>Country<span class="red">*</span></td>
<td><select id="country" name="country">
<option value="" selected>Please select...</option>
<option value="AA">AA</option>
<option value="BB">BB</option>
<option value="CC">CC</option>
</select><br /></td>
<td id="countryError" class="red"> </td></tr>
<tr>
<td>Gender<span class="red">*</span></td>
<td><input type="radio" name="gender" value="m" />Male
<input type="radio" name="gender" value="f" />Female</td>
<td id="genderError" class="red"> </td></tr>
<tr>
<td>Preferences<span class="red">*</span></td>
<td><input type="checkbox" name="color" value="r" />Red
<input type="checkbox" name="color" value="g" />Green
<input type="checkbox" name="color" value="b" />Blue</td>
<td id="colorError" class="red"> </td></tr>
<tr>
<td>Phone<span class="red">*</span></td>
<td><input type="text" id="phone" name="phone" /></td>
<td id="phoneError" class="red"> </td></tr>
<tr>
<td>Email<span class="red">*</span></td>
<td><input type="text" id="email" name="email" /></td>
<td id="emailError" class="red"> </td></tr>
<tr>
<td>password (6-8 characters)<span class="red">*</span></td>
<td><input type="password" id="password" name="password" /></td>
<td id="passwordError" class="red"> </td></tr>
<tr>
<td>Verify password<span class="red">*</span></td>
<td><input type="password" id="pwVerified" name="pwVerified" /></td>
<td id="pwVerifiedError" class="red"> </td></tr>
<tr>
<td> </td>
<td><input type="submit" value="SEND" id="submit"/>
<input type="reset" value="CLEAR" id="reset"/></td>
<td> </td></tr>
</table>
</form>
.red { /* for error messages */
color: red;
}
input.error { /* for the error input text fields */
border: 1px red inset;
padding: 2px;
}
table {
border: 0;
}
td {
margin: 0;
padding: 3px 10px 3px 3px;
}
window.onload = init;
// The "onload" handler. Run after the page is fully loaded.
function init() {
// Attach "onsubmit" handler
document.getElementById("theForm").onsubmit = validateForm;
// Attach "onclick" handler to "reset" button
document.getElementById("reset").onclick = clearDisplay;
// Set initial focus
document.getElementById("name").focus();
}
/* The "onsubmit" handler to validate the input fields.
* Most of the input validation functions take 2 arguments:
* inputId or inputName: the "id" of the <input> element to be validated
* or "name" for checkboxes and radio buttons.
* errorMsg: the error message to be displayed if validation fails.
* The message shall be displayed on an element with id of
* inputID+"Error" if it exists; otherwise via an alert().
*/
function validateForm() {
return (isNotEmpty("name", "Please enter your name!")
&& isNumeric("zipcode", "Please enter a valid postcode!")
&& isLengthMinMax("zipcode", "Please enter your postcode!", 7, 8)
&& isSelected("country", "Please make a selection!")
&& isChecked("gender", "Please check a gender!")
&& isChecked("color", "Please check a color!")
&& isNumeric("phone", "Please enter a valid phone number!")
&& isValidEmail("email", "Enter a valid email!")
&& isLengthMinMax("password", "Enter a valid password!", 6, 8)
&& verifyPassword("password", "pwVerified", "Different from the password!"));
}
// Return true if the input value is not empty
function isNotEmpty(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.length !== 0); // boolean
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
/* If "isValid" is false, print the errorMsg; else, reset to normal display.
* The errorMsg shall be displayed on errorElement if it exists;
* otherwise via an alert().
*/
function showMessage(isValid, inputElement, errorMsg, errorElement) {
if (!isValid) {
// Put up error message on errorElement or via alert()
if (errorElement !== null) {
errorElement.innerHTML = errorMsg;
} else {
alert(errorMsg);
}
// Change "class" of inputElement, so that CSS displays differently
if (inputElement !== null) {
inputElement.className = "error";
inputElement.focus();
}
} else {
// Reset to normal display
if (errorElement !== null) {
errorElement.innerHTML = "";
}
if (inputElement !== null) {
inputElement.className = "";
}
}
}
// Return true if the input value contains only digits (at least one)
function isNumeric(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.search(/^[0-9]+$/) !== -1);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
// Return true if the input value contains only letters (at least one)
function isAlphabetic(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = inputValue.match(/^[a-zA-Z]+$/);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
// Return true if the input value contains only digits and letters (at least one)
function isAlphanumeric(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = inputValue.match(/^[0-9a-zA-Z]+$/);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
// Return true if the input length is between minLength and maxLength
function isLengthMinMax(inputId, errorMsg, minLength, maxLength) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.length >= minLength) && (inputValue.length <= maxLength);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
// Return true if the input value is a valid email address
// (For illustration only. Should use regexe in production.)
function isValidEmail(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value;
var atPos = inputValue.indexOf("@");
var dotPos = inputValue.lastIndexOf(".");
var isValid = (atPos > 0) && (dotPos > atPos + 1) && (inputValue.length > dotPos + 2);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
// Return true if selection is made (not default of "") in <select> input
function isSelected(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value;
// You need to set the default value of <select>'s <option> to "".
var isValid = inputValue !== "";
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
// Return true if the one of the checkboxes or radio buttons is checked
function isChecked(inputName, errorMsg) {
var inputElements = document.getElementsByName(inputName);
var errorElement = document.getElementById(inputName + "Error");
var isChecked = false;
for (var i = 0; i < inputElements.length; i++) {
if (inputElements[i].checked) {
isChecked = true; // found one element checked
break;
}
}
showMessage(isChecked, null, errorMsg, errorElement);
return isChecked;
}
// Verify password. The password is kept in element with id "pwId".
// The verified password in id "verifiedPwId".
function verifyPassword(pwId, verifiedPwId, errorMsg) {
var pwElement = document.getElementById(pwId);
var verifiedPwElement = document.getElementById(verifiedPwId);
var errorElement = document.getElementById(verifiedPwId + "Error");
var isTheSame = (pwElement.value === verifiedPwElement.value);
showMessage(isTheSame, verifiedPwElement, errorMsg, errorElement);
return isTheSame;
}
// The "onclick" handler for the "reset" button to clear the display
function clearDisplay() {
var elms = document.getElementsByTagName("*"); // all tags
for (var i = 0; i < elms.length; i++) {
if ((elms[i].id).match(/Error$/)) { // no endsWith() in JS?
elms[i].innerHTML = "";
}
if (elms[i].className === "error") { // assume only one class
elms[i].className = "";
}
}
// Set initial focus
document.getElementById("name").focus();
}