Feed Rss



Feb 27 2008

Validation

category: PHP,Tutorials author:

n this day and age and taking into consideration the evolution of the web, allot of things are overlooked when programming and one of the main subjects I see commonly being 223overlooked" is validation.

Validation isn't that difficult you just need to question the integrity of every string trying to be parsed, the most common use of validation is along side forms and that's what I am going to be discussing today.

Let's start with a simple form with a name, age, e-mail and comments form objects.

<form method="post">
<input type="text" name="name">
<input type="text" name="age">
<input type="text" name="email">
<textarea name="comments"> </textarea>
<input type="submit" name="submit">
</form>

Now, usually when a form is posted all the values are parsed and if we are using an e-mail script to send an e-mail then the e-mail script is venerable of being attacked using a technique called 223e-mail injection", this means that people can parse more information then you want them to.

Let's start with the name field, it is a required field so we need to validate that the name field has a value, to do this I am going to test the integrity of the value parsed using the function empty (http://uk3.php.net/empty). This is how I would see if the field name is 223empty".

<?
If (empty($_POST['name']))
{
$errors[] = 'Please enter a name';
}
?>

As you can see from the above example I initiated an array called errors and added the value please enter a name, this array will be used later.

The next field is the age field, now because the value of the field should be a numeric value we will also check to see if the value parsed is numeric using the is_numeric (http://uk3.php.net/is_numeric) function like so.

<?
if (empty($_POST['age']))
{
$errors[] = 'Please enter a age';
}
else if (!is_numeric($_POST['age']))
{
$errors[] = 'Please enter a valid age with a numeric value';
}
?>

Next we need to validate the e-mail address, I have seen this done many ways but the best way in my opinion is with a regular expression, so something like this should be sufficient enough to stop people trying to parse multiple e-mail addresses.

<?
if (empty($_POST['email']))
{
$errors[] = 'Please enter an e-mail';
}
else if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_POST['email']))
{
$errors[] = 'Please enter a valid e-mail address';
}
?>

Finally comments, identical to the name field although because the comments field is a textarea we do not have any control over the length of the value, so if you think it's necessary you can add a length check like this.

<?
if (empty($_POST['comments']))
{
$errors[] = 'Please enter some comments';
}
else if (strlen ($_POST['comments']) > 255)
{
$errors[] = 'Your comment is too long, please do not submit more then 255 characters';
}
?>

Then once all the validation fields have been assigned you can utilize the error messages (if they exist) like so.

if (count($errors) == 0)
{
// Process form
}
else
{
echo $errors[0];
}

That's basically the round trip of validation, these are very important aspects of maintaining secure forms, just to make things easier here is the code in full and i have added a html table with labels for each field.

<?
if (empty($_POST['name']))
{
$errors[] = 'Please enter a name';
}

if (empty($_POST['age']))
{
$errors[] = 'Please enter a age';
}
else if (!is_numeric($_POST['age']))
{
$errors[] = 'Please enter a valid age with a numeric value';
}

if (empty($_POST['email']))
{
$errors[] = 'Please enter an e-mail';
}
else if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_POST['email']))
{
$errors[] = 'Please enter a valid e-mail address';
}

if (empty($_POST['comments']))
{
$errors[] = 'Please enter some comments';
}
else if (strlen ($_POST['comments']) > 255)
{
$errors[] = 'Your comment is too long, please do not submit more then 255 characters';
}

if (count($errors) == 0)
{
// Process form
}
else
{
echo $errors[0];
}
?>

<form method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>E-mail:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Comments:</td>
<td><input name="comments" ></td>
</tr>
<tr>
<td colspan="2"><textarea name="comments"> </textarea></td>
</tr>
</table>
</form>

if you do have any other questions then please leave a comment below.

tag: , ,

17 Responses to “Validation”

  1. Sheraz says:

    That's a good code especially email validation is a little bit outstanding. but i am searching for a code that could check the alphabits and integers.kindly if you could find then mail me

  2. kevin says:

    Like Sheraz I am looking for a function that can be used for a name field whereby it will allow numbers and the alphabet only I found the following function but it didn't work
    function check_field1($field_name_1)

    {
    if(preg_match("/[^a-zA-Z0-9.-\304\344\326\366\334\374\r
    ]+$/s",$field_name_1))
    return TRUE;
    else
    return FALSE;
    }
    would the be called by
    if(!check_field1(variable)){
    die('invalid entry')
    }

  3. lotsofcode says:

    This is a basic example of checking for only letters in the alphabet.

    function checkAlpha($string)
    {
    if (preg_match("/^([A-Za-z])+$/i", $string)) {
    return true;
    }
    return false;
    }

    $word = 'toodaloo';
    if (!checkAlpha($word)) {
    exit('only aplhabetical chars allowed');
    }

    $word2 = 'tooda1loo';
    if (!checkAlpha($word2)) {
    exit('only aplhabetical chars allowed for "'.$word2.'"');
    }

  4. Cory says:

    I just want to thank you for your simple step by step validation process. I had been searching for such a tutorial for some time and all I got was advanced stuff that I did not understand.

  5. Uranius says:

    Thanks for this it was really helpful :)

  6. misganu fekadu says:

    this is very nice thing thank you!

  7. fadil says:

    nice... one of the best in my eyes.. :-)

    but i note what have been keyed in is reset whenever there's an error.. how can we make it stay?

  8. ren says:

    hiey! thanks for this.. thank you very much! :D

  9. ren says:

    do you have xamples on how to detect the zodiac signs?. thank you very much.

  10. aryan says:

    i want phone validations

  11. pavan says:

    i want display at a time all errors, and i need phone validations also i need how insert and edit and deleted exciting details. in database.

  12. Spacebabe says:

    Love ur code en how simply u explain it - very cool. Just one request, though: how do u make sure that the form retains the other correct values? I would really appreciate a reply... thanx.

  13. gyver says:

    what if about update?..
    i want to update my data base in my account..
    if my last name is stored in a database..
    it should be a msg box like "lastname is allready in used"
    what if i want to update my first name and not my last name..
    i want to know the code..
    this is what i want..

    Last Name: Yeoh
    First Name: Gyver
    i want to change my first name into Mac..
    i want to have a msg box like this "Updated successfully"
    help me pls..
    using xampp

  14. Emma says:

    Thanks so much, There isn't a php validation site that is as helpful as yours or that is in simplistic terms for beginners.

    absolute champion!! thanks !!

  15. eheuristic says:

    How I can do Validation in php?
    can you plz tell me??

  16. azar says:

    Thx i am looking for this........

    And Also

    How to validate database duplicate in php

  17. paul says:

    Cant figure out how to add just the email validation to this.

    can you help??

    function privacy_form($idnum)
    {

    global $ct, $tbclr_1, $tbclr_2, $tbclr_3, $tbclr_4, $fntclr_1, $emltp, $emllogin, $msg2, $indx_url ;

    $fields_val=get_edit_info($idnum);
    $message= "


    ".$msg2['ID_f']."".$fields_val['idnum']."   ".$fields_val['title']."

      ".$msg2['Send_Privacy_Message']."

     

    ".$msg2['Your_e_mail_f'].":

    ".$msg2['Subject_p'].":

    ".$msg2['Message_p'].":

    ";
    $message=$message."

    ";
    output_message($message);
    return;
    }

Leave a Reply