Form validation
by Ajay Patel
HTML
<div id="error">Error! Please check your information.</div>
<form id="contact">
<p>Title:
<select id="title">
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss.">Miss.</option>
</select>
</p>
<p>First name: <input id="first" /> </p>
<p>Last name: <input id="last" /> </p>
<p>Email: <input id="email" /> </p>
<p>Zip: <input id="zip" /> </p>
<p>Phone: <input id="phone" /> </p>
<p> <input type="submit" value="Submit" /> </p>
</form>
<div id="result"> </div>
CSS
#error {
color: red;
border: 1px solid red;
padding: 5px;
display: none;
}
#result {
padding: 20px;
}
p {
display: block;
text-align: right;
}
input, select {
width: 100px;
}
JavaScript
function Validate() {
// first we clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
// we start by assuming everything is correct
// if it later turns out not to be, we just set
// this to false
var correct = true;
// we can't tell much about valid names, so we
// just make sure the field isn't empty
if ($('#first').val() == '') {
error.append('<p>No first name provided</p>');
correct = false;
}
// ditto for last name
if ($('#last').val() == '') {
error.append('<p>No last name provided</p>');
correct = false;
}
// emails we can guess more about, so grab a copy
var email = $('#email').val();
// first we check if the email field is empty
if (email == '') {
error.append('<p>No email provided</p>');
correct = false;
}
// if it isn't empty, we check for an @ sign
else if (email.indexOf('@') == -1) {
error.append('<p>Email does not contain @ symbol</p>');
correct = false;
}
// if it has an @ sign, we need to check for a dot
// after the @ sign
else if (email.lastIndexOf('.') < email.indexOf('@')) {
error.append('<p>Email does not contain a . (full stop)</p>');
correct = false;
}
// zip codes we know have to be 5 digits, so check the length
if ($('#zip').val().length != 5) {
error.append('<p>Zip code must be 5 digits</p>');
correct = false;
}
// zip codes we know have to be 5 digits, so check the length
if ($('#phone').val().length != 10) {
error.append('<p>Mobile no must be 10 digits</p>');
correct = false;
}
// if we haven't found an error, we hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
...