• php
  • 6686
  • 20-3-2008
  • Whenever you make a form you should not leave it alone without any form validation. Why? Because there is no guarantee that the input is correct and processing incorrect input values can make your application give unpredictable result. You can validate the form input on two places, client side and server side. Client side form validation usually done with javascript. Client side validation makes your web application respond 'faster' while server side form validation with PHP can act as a backup just in case the user switch off javascript support on her browser. And since different browsers can behave differently there is always a possibility that the browser didn't execute the javascript code as you intended.

    Some things you need to check : - empty values
    - numbers only
    - input length
    - email address
    - strip html tags To show form validation with php in action I'll use the contact form in this website. Click here to see the contact form and then take a look at the source code. This contact form requires four input : - sender name
    - sender email
    - message subject
    - message body First let's focus on the client side validation. On the "Send Message" button I put this javascript code : [color=A4D867]onClick="return checkForm();",[/color] which is triggered when you click on it. Clicking the button will run the function [color=F6C9D2]checkForm().[/color]Every input is checked to see whether they are valid input. When an invalid input is found the function returns [color=A4D867]false[/color] so the form is not submitted. When you insert valid input the function will return [color=A4D867]true[/color] and the form is submitted.

    Go ahead and play around with the form. Try entering only spaces for the input value or enter glibberish string as email address. The code snippet below shows the client part of contact form.
    <html>
    <head>
    <title>Contact Form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <style type="text/css"> // CSS goes here </style>
    <script language="JavaScript">
    function checkForm()
    {
    var cname, cemail, csubject, cmessage;
    with(window.document.msgform)
    {
    cname = sname;
    cemail = email;
    csubject = subject;
    cmessage = message;
    } if(trim(cname.value) == '')
    {
    alert('Please enter your name');
    cname.focus();
    return false;
    }
    else if(trim(cemail.value) == '')
    {
    alert('Please enter your email');
    cemail.focus();
    return false;
    }
    else if(!isEmail(trim(cemail.value)))
    {
    alert('Email address is not valid');
    cemail.focus();
    return false;
    }
    else if(trim(csubject.value) == '')
    {
    alert('Please enter message subject');
    csubject.focus();
    return false;
    }
    else if(trim(cmessage.value) == '')
    {
    alert('Please enter your message');
    cmessage.focus();
    return false;
    }
    else
    {
    cname.value = trim(cname.value);
    cemail.value = trim(cemail.value);
    csubject.value = trim(csubject.value);
    cmessage.value = trim(cmessage.value);
    return true;
    }
    } function trim(str)
    {
    return str.replace(/^\s+|\s+$/g,'');
    } function isEmail(str)
    {
    var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag|
    ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|
    bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|
    ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|
    dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|
    gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|
    hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|
    kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|
    ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|
    mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|
    nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|
    re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|
    su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|
    ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|
    zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i; return regex.test(str);
    }
    </script>
    </head>
    <body>
    <form method="post" name="msgform">
    <table width="500" border="0" align="center" cellpadding="2" cellspacing="1" class="maincell">
    <tr>
    <td width="106">Your Name</td>
    <td width="381"><input name="sname" type="text" class="box" id="sname" size="30"></td>
    </tr>
    <tr>
    <td>Your Email</td>
    <td>
    <input name="email" type="text" class="box" id="email" size="30">
    </td></tr>
    <tr>
    <td>Subject</td>
    <td><input name="subject" type="text" class="box" id="subject" size="30"></td>
    </tr>
    <tr>
    <td>Message</td>
    <td><textarea name="message" cols="55" rows="10" wrap="OFF" class="box" id="message"></textarea></td>
    </tr>
    <tr align="center">
    <td colspan="2"><input name="send" type="submit" class="bluebox" id="send" value="Send Message" onClick="return checkForm();"></td>
    </tr>
    <tr align="center">
    <td colspan="2"> </td>
    </tr>
    </table>
    </form>
    </body>
    </html>
    Now we'll take a better look at [color=144273]checkForm()[/color] function :
    function checkForm()
    {
    var cname, cemail, csubject, cmessage;
    with(window.document.msgform)
    {
    cname = sname;
    cemail = email;
    csubject = subject;
    cmessage = message;
    } // ... the rest of the code }

    In the beginning of the function I use the keyword var to declare four variables to reference the form input . They are cname, cemail, csubject and cmessage. These variables will reference the form input sname, email, subject and message respectively.
    Javascript treats a document and it's element as object. The message form is named msgform so to access is we use window.document.msgform and to access the sname input text we can use window.document.msgform.sname. To avoid the hassle of writing the window.document.msgform part whenever we want to access a form object I use the with() keyword. Without it the checkForm() function would look like :
    function checkForm()
    {
    var cname, cemail, csubject, cmessage;

    cname = window.document.msgform.sname;
    cemail = window.document.msgform.email;
    csubject = window.document.msgform.subject;
    cmessage = window.document.msgform.message;
    // ... the rest of the code }

    Next we'll validate each form input.
    function checkForm()
    {
    // variable declarations goes here ... if(trim(cname.value) == '')
    {
    alert('Please enter your name');
    cname.focus();
    return false;
    }
    else if(trim(cemail.value) == '')
    {
    alert('Please enter your email');
    cemail.focus();
    return false;
    }
    else if(!isEmail(trim(cemail.value)))
    {
    alert('Email address is not valid');
    cemail.focus();
    return false;
    }
    // The rest of validation code goes here ...
    }

    To access the value of the name input box we use cname.value. The name values is trimmed to remove extra spaces from the beginning and end of the name. If you do not enter your name or only entering spaces then an alert box will pop up. Using cname.focus() the cursor will be placed to the name input box and then checkForm() return false which cancel the form submit.
    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
    ?>

    The PHP validation is doing the same thing as the javascript validation. It check each value to see if it's empty and if it is we consider that as an error. We also recheck the validity of the email address. When we find an error we set the value of $errmsg. We will print this value so the user can fix the error. If everything is okay the value of $errmsg will be blank. So we continue processing the input.
    <?php // ... previous validation code if($errmsg == '')
    {
    if(get_magic_quotes_gpc())
    {
    $subject = stripslashes($subject);
    $message = stripslashes($message);
    } $to = "email@yourdomain.com";
    $subject = '[Contact] : ' . $subject;
    $msg = "From : $sname \r\n " . $message;
    mail($to,
    $subject,
    $msg,
    "From: $email\r\nReturn-Path: $email\r\n"); // ... more code here
    ?>

    Some web host set the PHP directive magic_quotes_gpc to 'on' which runs addslashes() to every GET, POST, and COOKIE data so we got an extra work to strip the slashes from the input. Because the addslashes() function only add slashes before single quote ( ' ), double quote ( " ), backslash ( \ ) and NULL, we only need to worry about the $subject and $message. This is because (usually ) only these two can contain such characters. However, we can't be sure if magic_quotes_gpc is On or Off so we have to check it's value first using the get_magic_quotes_gpc() function After finishing all that boring job of validating the input we finally come to the last, and the most important step, sending the message using the mail() function. The first parameter we pass to the mail() function is the receiver's email address. The second is the email subject. The third is the message itself and the fourth is an additional headers. I'm sure you already understand the purpose of the first three parameters so I'll just discuss about the fourth one, the additional parameter ( additional headers ) [color=A4D867]"From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"[/color] Each headers are separated by the "\r\n" ( newline ) characters. The first two ( From and Reply-To ) is self explanatory. But what about the third one ( Return-Path )? The reason is some spam filter will check the Return-Path header and compare it with the From header. If these two don't match then the email is considered as spam and you're email won't get delivered ( or sent to the spam folder ). So it's better to play safe and put Return-Path header when we want to send an email to make sure it gets delivered.
    كن أول من يقيم الموضوع
    12345