The code above uses trim() function. This is
not a built in javascript function. I can't understand why there is no
trim() function in javascript, even VBScript has it. Anyway it's not
a big deal because we can just make our own trim() function.
The solution here uses regular expression to replace any spaces
in the beginning and end of a string with blank string.
function trim(str)
{
return str.replace(/^\s+|\s+$/g,'');
}
The forward slash (/) is used to create a regular
expression. Note that it is not a string, you don't have to
use quotes and it won't work if you use quotes. Let's chop the regular expression
notation so we can understand it better :
- ^ : the beginning of a string
- $ : end of string.
- \s : single whitespace character
(tab also count as whitespace)
- + : one or more
- | : conditional (OR)
- g : global, mainly used for
search and replace operation
So in english the search replace function above can be read as :
"Replace one or more whitespace character from the beginning
or ending of a string with blank character"
As for the email input, we need to double check it. First, check if the email
is entered and second check if the input is in a valid email format. For the
second check well use isEmail() function. This function also uses regular expression.
A valid email format can be described as :
[ a string consisting of alphanumeric characters, underscores,
dots or dash ] @ ( [ a valid domain name ] DOT [ a valid TLD ]) OR [a valid
IP adress ]
In case you're wondering TLD means Top Level Domain such as com, net, org,
biz, etc.
When you see the source
code you will see that the regular expression in isEmail()
function is actually written in one line. I have to break them into multiple
lines just to fit the space. The PHP Manual explains the regular expression
syntax for PHP in depth, but if you want to learn regular expression for javascript
you can go to : http://www.regular-expressions.info
Finally, if all input are considered valid checkForm()
returns true and the form will be submitted.
This will set the $_POST['send'] variable and now
we start validating the input on the server side using PHP.
<?php
$errmsg = ''; // error message
$sname = ''; // sender's name
$email = ''; // sender's email addres
$subject = ''; // message subject
$message = ''; // the message itself
if(isset($_POST['send']))
{
$sname = $_POST['sname'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if(trim($sname) == '')
{
$errmsg = 'Please enter your name';
}
else if(trim($email) == '')
{
$errmsg = 'Please enter your email address';
}
else if(!isEmail($email))
{
$errmsg = 'Your email address is not valid';
}
else if(trim($subject) == '')
{
$errmsg = 'Please enter message subject';
}
else if(trim($message) == '')
{
$errmsg = 'Please enter your message';
}
// ... more code here
?>
|