William
William

Reputation: 6610

Website Form Validation

I am currently designing a website and database solution which allows an administrator to login and view/add/edit/delete data held in the database.

What is the best way to go about form validation for details the person will enter into these forms;

i.e. dates must have the convention xx/xx/xx

Upvotes: 1

Views: 148

Answers (2)

MMM
MMM

Reputation: 7310

There are many different ways of validating such data but the most popular one is using regular expressions. You probably also want to check other things after validating the data format.

For instance if you want to check your date you can do the following:

function checkDateFormat($date)
{
//match the format of the date
  if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
  //check weather the date is valid of not
    if(checkdate($parts[2],$parts[3],$parts[1]))
      return true;
    else
      return false;
  } else {
    return false;
  }
}

This will not only check the format of the date (in this case yyyy/mm/dd but you can modify it slightly to support yy/mm/dd or whichever order you want) but also will check if it is a valid date (e.g. 2001/02/31 is not a valid date).

Upvotes: 1

tonymarschall
tonymarschall

Reputation: 3882

You can do this native or by libraries like.

Native:

//If form was submitted  
if ($_POST['submitted']==1) {  
  // check date format, ...
  if ($_POST[date]){  
    $date = $_POST[date]; //If date was entered  
  }  
  ...
}  

Or by library: http://pear.php.net/package/HTML_QuickForm2

<?php
require_once 'HTML/QuickForm2.php';
require_once 'HTML/QuickForm2/Rule/Required.php';
require_once 'HTML/QuickForm2/Rule/Regex.php';

$form = new HTML_QuickForm2('tutorial');
$username = $form->addElement('text', 'username');
$form->addElement('submit', null, array('value' => 'Send!'));

$username->addRule(new HTML_QuickForm2_Rule_Required(
    $username, 'Username is required!'
));
....

Upvotes: 0

Related Questions