0

please could someone help me for a code to validate DOB i got this code on the web but doesnt work i want to validate dd/mm/yyyy or any other format is fine by me.

  if(preg_match("/dob/i",$field))
        {
       if(!preg_match("“/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/”",$value)) code from web
          {
            $errors[]="$value is not a valid dob please enter only year.";
          } 
        }
7
Contributors
13
Replies
16
Views
4 Years
Discussion Span
Last Post by diafol
Featured Replies
  • 1
    diafol 3,669   4 Years Ago

    Yep agree, datepicker will enable you to decide which format to display the date (and possibly which format to send - depending on the datepicker itself). However, validation and error-checking/reporting is still your call. The code included with the datepicker may have server-side code for this purpose, but usually not … Read More

0

The format will determine what functions you need to use.

strtotime() is a pretty good catch-all. However dates of this format xx/xx/xxxx will default to US format: m/d/Y and xx-xx-xxxx will default to European d-m-Y.

If your date format is known to be 'd/m/Y', then you can explode it to get the parts (day, month, year) and then use checkdate() to ensure that it's valid.

$parts = explode("/",$date); //if d/m/Y
if(checkdate($parts[1],$parts[0],$parts[2]){...}

Alternatively, you can use date_parse_from_format():

$parts = date_parse_from_format("d/m/Y", $date);

And then do the checkdate:

if(checkdate($parts['month'],$parts['day'],$parts['year']){...}

There are loads of functions, have a look here for a list:

http://www.php.net/manual/en/ref.datetime.php

Here's a simple function and use:

<?php

function dateCheck($date,$format='d/m/Y'){
    $parts = date_parse_from_format($format, $date);
    return (checkdate($parts['month'],$parts['day'],$parts['year'])) ? true : false;
}

$date = "13-12-2012";
echo (dateCheck($date,'d-m-Y')) ? "Date $date is true" : "Date $date is false";

$date2 = "18/09/2011";
echo (dateCheck($date2)) ? "Date $date2 is true" : "Date $date2 is false";

?>

Notice the default d/m/Y format. No need to supply this as a parameter.

Edited by diafol

0

thanks,
i will follow this method and see how it goes, thanks for your time

0

Hello i used the your code but i get this error messageDate 13-12-2012 is trueDate 18/09/2011 is true Fatal error: Cannot redeclare dateCheck() (previously declared in C:\Users\0382\xampp\htdocs\dia\source\Login.php:149) in C:\Users\0382\xampp\htdocs\dia\source\Login.php on line 149

below is my code where i pasted it pls could you check if i have pasted it in the corect place?

 /* validate data */
    foreach($_POST as $field => $value)                 
    {
      if(!empty($value))                                
      {
        if(preg_match("/name/i",$field) and
          !preg_match("/user/i",$field) and 
          !preg_match("/log/i",$field))
        {
          if (!preg_match("/^[A-Za-z' -]{1,50}$/",$value)) 
          {
             $errors[] = "$value is not a valid name. "; 
          }
        }
        if(preg_match("/street/i",$field) or 
           preg_match("/addr/i",$field) or
           preg_match("/city/i",$field))
        {
          if(!preg_match("/^[A-Za-z0-9.,' -]{1,50}$/", 
                          $value))
          {
            $errors[] = "$value is not a valid address 
                          or city.";
          }
        }
        if(preg_match("/state/i",$field))
        {
          if(!preg_match("/^[A-Z][A-Z]$/",$value))
          {
            $errors[] = "$value is not a valid state code.";
          }
        }
        if(preg_match("/email/i",$field)or
           preg_match("/fbook/i",$field) or 
           preg_match("/twitter/i",$field))
        {
          if(!preg_match("/^.+@.+\\..+$/",$value))
          {
            $errors[]="$value is not a valid address.";
          }
        }
        if(preg_match("/zip/i",$field))
        {
          if(!preg_match("/^[0-9]{5}(\-[0-9]{4})?$/",$value))
          {
            $errors[] = "$value is not a valid zipcode. ";
          }
        }
        if(preg_match("/phone/i",$field) or 
           preg_match("/fax/i",$field))
        {
          if(!preg_match("/^[0-9)(xX -]{7,20}$/",$value))
          {
            $errors[]="$value is not a valid phone number.";
          }
        }
         if(preg_match("/dcompleted/i",$field))
        {
       if(!preg_match("/^[0-4)(xX -]{1,4}$/",$value))
          {
            $errors[]="$value is not a valid year please enter only year.";
          } 
        } 
    //ddate of birth

    function dateCheck($date,$format='d/m/Y'){
    $parts = date_parse_from_format($format, $date);
    return (checkdate($parts['month'],$parts['day'],$parts['year'])) ? true : false;
    }
    $date = "13-12-2012";
    echo (dateCheck($date,'d-m-Y')) ? "Date $date is true" : "Date $date is false";
    $date2 = "18/09/2011";
    echo (dateCheck($date2)) ? "Date $date2 is true" : "Date $date2 is false";
      } // end if not empty                            
    } 
0

Sorry i only sent the validation section only but this is the whole page

<?php
/* Program: Login.php
 * Desc:    Main application script for the User Login
 *          application. It provides two options: 
 *          (1) login using an existing username and 
 *          (2) register a new username. 
 *
 *    ob_start();
  */
 session_start();                                          
switch (@$_POST['Button'])                               
{
  case "Log in":                                        
    include("dogs.inc");                                
    $cxn = mysqli_connect($host,$user,$passwd,$dbname)
             or die("Query died: connect");             
    $sql = "SELECT loginName FROM Member 
              WHERE loginName='$_POST[fusername]'";
    $result = mysqli_query($cxn,$sql)
                or die("Query died: fusername: ".mysqli_error($cxn));
    $num = mysqli_num_rows($result);                     
    if($num > 0)  //login name was found                
    {
      $sql = "SELECT loginName FROM Member 
              WHERE loginName='$_POST[fusername]'
              AND password=md5('$_POST[fpassword]')";
      $result2 = mysqli_query($cxn,$sql)
                   or die("Query died: fpassword");      
      $num2 = mysqli_num_rows($result2);                
      if($num2 > 0)  //password matches                  
      {
        $_SESSION['auth']="yes";                        
        $_SESSION['logname'] = $_POST['fusername'];      
        $sql = "INSERT INTO Login (loginName,loginTime)
                VALUES ('$_SESSION[logname]',NOW())";
        $result = mysqli_query($cxn,$sql)
                   or die("Query died: insert");        
        header("Location: SecretPage.php");             
      }
      else  // password does not match                   
      {
        $message_1="The Login Name, '$_POST[fusername]' 
                exists, but you have not entered the 
                correct password! Please try again.";
        $fusername = strip_tags(trim($_POST['fusername']));
        include("login_form.inc");
      }                                                  
    }                                                    
    else  // login name not found                        
    {
      $message_1 = "The User Name you entered does not 
                    exist! Please try again.";
      include("login_form.inc");
    }
  break;                                                

  case "Register":                                       
   /* Check for blanks */
    foreach($_POST as $field => $value)                 
    {
      if($field != "fax")                               
      {
        if(empty($value))
        {
          $blanks[] = $field;
        }
        else
        {
          $good_data[$field] = strip_tags(trim($value));
        }
      }
    }                                                    
    if(isset($blanks))                                   
    {
      $message_2 = "The following fields are blank. 
            Please enter the required information:  ";
      foreach($blanks as $value)
      {
        $message_2 .="$value, ";
      }
      extract($good_data);                              
      include("login_form.inc");
      exit();                                           
    }                                                  
  /* validate data */
    foreach($_POST as $field => $value)                 
    {
      if(!empty($value))                                
      {
        if(preg_match("/name/i",$field) and
          !preg_match("/user/i",$field) and 
          !preg_match("/log/i",$field))
        {
          if (!preg_match("/^[A-Za-z' -]{1,50}$/",$value)) 
          {
             $errors[] = "$value is not a valid name. "; 
          }
        }
        if(preg_match("/street/i",$field) or 
           preg_match("/addr/i",$field) or
           preg_match("/city/i",$field))
        {
          if(!preg_match("/^[A-Za-z0-9.,' -]{1,50}$/", 
                          $value))
          {
            $errors[] = "$value is not a valid address 
                          or city.";
          }
        }
        if(preg_match("/state/i",$field))
        {
          if(!preg_match("/^[A-Z][A-Z]$/",$value))
          {
            $errors[] = "$value is not a valid state code.";
          }
        }
        if(preg_match("/email/i",$field)or
           preg_match("/fbook/i",$field) or 
           preg_match("/twitter/i",$field))
        {
          if(!preg_match("/^.+@.+\\..+$/",$value))
          {
            $errors[]="$value is not a valid address.";
          }
        }
        if(preg_match("/zip/i",$field))
        {
          if(!preg_match("/^[0-9]{5}(\-[0-9]{4})?$/",$value))
          {
            $errors[] = "$value is not a valid zipcode. ";
          }
        }
        if(preg_match("/phone/i",$field) or 
           preg_match("/fax/i",$field))
        {
          if(!preg_match("/^[0-9)(xX -]{7,20}$/",$value))
          {
            $errors[]="$value is not a valid phone number.";
          }
        }
         if(preg_match("/dcompleted/i",$field))
        {
       if(!preg_match("/^[0-4)(xX -]{1,4}$/",$value))
          {
            $errors[]="$value is not a valid year please enter only year.";
          } 
        }

    function dateCheck($date,$format='d/m/Y'){    //line 149
    $parts = date_parse_from_format($format, $date);
    return (checkdate($parts['month'],$parts['day'],$parts['year'])) ? true : false;
    }
    $date = "13-12-2012";
    echo (dateCheck($date,'d-m-Y')) ? "Date $date is true" : "Date $date is false";
    $date2 = "18/09/2011";
    echo (dateCheck($date2)) ? "Date $date2 is true" : "Date $date2 is false";
      } // end if not empty                            
    } 
    foreach($_POST as $field => $value)                 
    {                                                  
      $$field = strip_tags(trim($value));
    }
    if(@is_array($errors))                             
    { 
      $message_2 = "";
      foreach($errors as $value)
      {
        $message_2 .= $value." Please try again<br />";
      }
      include("login_form.inc");
      exit();
    } // end if errors are found                       

   /* check to see if user name already exists */
    include("dogs.inc");                                
    $cxn = mysqli_connect($host,$user,$passwd,$dbname)
             or die("Couldn't connect to server");
    $sql = "SELECT loginName FROM Member 
                WHERE loginName='$loginName'";          
    $result = mysqli_query($cxn,$sql)
                or die("Query died: loginName.");
    $num = mysqli_num_rows($result);                    
    if($num > 0)                                        
    {
      $message_2 = "$loginName already used. Select 
                       another User Name.";
      include("login_form.inc");
      exit();
    } // end if user name already exists
    else // Add new member to database                  
    {   
      $sql = "INSERT INTO Member (loginName,createDate,
                password,firstName,lastName,street,city,
                state,zip,phone,fax,email,nationality,gender, dob,fbook,twitter,school,academic,ref,dcompleted,pstudied,lang) VALUES
              ('$loginName',NOW(),md5('$password'),
               '$firstName', '$lastName','$street','$city',
               '$state','$zip','$phone','$fax','$email','$nationality','$gender','$dob','$fbook','$twitter',
               '$school','$academic','$ref','$dcompleted','$pstudied','$lang')";
      mysqli_query($cxn,$sql);                          
      $_SESSION['auth']="yes";                          
      $_SESSION['logname'] = $loginName;                
      /* send email to new Customer */
      $emess = "You have successfully registered. ";
      $emess .= "Your new user name and password are: ";
      $emess .= "\n\n\t$loginName\n\t";
      $emess .= "$password\n\n";
      $emess .= "We appreciate your interest. \n\n";
      $emess .= "If you have any questions or problems,";
      $emess .= " email onofej@gmail.com";          
      $subj = "Your new customer registration";         
      $mailsend=mail("$email","$subj","$emess");       
      header("Location: New_member.php");               
        } 
  break;                                                

  default:                                              
    include("login_form.inc");
}  
?>
0

Hello i used the your code but i get this error messageDate 13-12-2012 is trueDate 18/09/2011 is true Fatal error: Cannot redeclare dateCheck() (previously declared in C:\Users\0382\xampp\htdocs\dia\source\Login.php:149) in C:\Users\0382\xampp\htdocs\dia\source\Login.php on line 149

You've declared the function, dateCheck() within a loop. Define the function above the loop.

Another point is that preg_match is a relatively slow function. You don't need to use it when '==' will suffice.

For example this snippet:

if(preg_match("/street/i",$field) or
preg_match("/addr/i",$field) or
preg_match("/city/i",$field))

Can be simplified to:

if($field == 'street' || $field == 'addr' || $field == 'city') { //...

That is easier to read and maintain and will run faster too.

0

thanks for your reply please checking my code what number/line do you think i should place the function, because i placeed it on line 85 and got an error i know i am not sure where the function should be exactly

0
<?php
//$datestr = '25-5-2012';
$datestr = '25-MAY-2012';
//$datestr = 'TEMP';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($datestr)) === false) {
    echo "The string ($datestr) is bogus";
} else {
    echo "$datestr == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}
?>

http://php.net/manual/en/function.strtotime.php

0

I always force the user to enter 3 separate fields, day month year into three inputs, text or select, and eliminate the ability for users to make errors
a sele3ct field of 1-31, a select filed of text months with values 1-12 antext field for year.
it is simple then to validate dates,\9if month=4 day is less than 31, and they still store as a single sql timestamp

I can't wait to get the bandages of my hands, I type like crap at the moment and can't be _____ correcting it

Edited by almostbob

0

Dear every one,
i have tried all the codes on this page and it all works, but when a user entered any thing wrong, it does not give error message to prompt the user to enter it again else it just give a warning message which will be frustrating to the user. please could someone help?

0

it does not give error message to prompt the user to enter it again

That is up to you. You should redirect back to the page and make a nice prompt. Personally, I'd go with the date picker, much less chance of trouble.

1

Yep agree, datepicker will enable you to decide which format to display the date (and possibly which format to send - depending on the datepicker itself). However, validation and error-checking/reporting is still your call. The code included with the datepicker may have server-side code for this purpose, but usually not in my experience. You can use a number of built-in php functions for general validation, but I don't know of one for 'date'. So it's probably up to you to provide this functionality.

You may need this as somebody may decide to spoof your form and send all manner of nonsense to your server. So, you cannot depend on receiving valid 'date' info. Defence in Depth is essential when dealing with passed form variables.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.