This question already has answers here:
My pattern isn't matching a ISO style date, why? [duplicate]
(3 answers)
Closed 7 years ago.
apologies for probably a simple question, but i am new to PHP and Javascript.
I am creating a login validation in PHP that requires a registering user to input their date of birth in a DD/MM/YYYY Format, that returns an error message if the date is entered in any other format. I am unsure how to do this, other than using preg_match, however this doesnt seem to work...
variables:
$DOB = $_POST['DOB'];
$error_message = '';
The Date Validation Segment
elseif (!preg_match("/^(0?[1-9]|[12][0-9]|3[01])\/\.- \/\.- \d{2}$/", $DOB))
{
$error_message = 'Invalid Date';
}
Error Display
if ($error_message != '')
{
echo 'Error: '.$error_message.' Go Back.';
echo '</body> </html>';
exit;
}
else
{
echo'<p><strong>Form Submitted Successfully!</strong></p>';
}
This is not a duplicate, i tried other threads and none of their solutions worked.
You should use more than a regular expression. For example, you should not allow something like 31/02/2015, because there's no 31th in February!
I have a function that works well:
function isDate($string) {
$matches = array();
$pattern = '/^([0-9]{1,2})\\/([0-9]{1,2})\\/([0-9]{4})$/';
if (!preg_match($pattern, $string, $matches)) return false;
if (!checkdate($matches[2], $matches[1], $matches[3])) return false;
return true;
}
It first uses preg_match to check for the formal validity of DD/MM/YYYY, grabbing DD, MM and YYYY portions into the $matches array. Then it check the validity of the date itself using the built-in PHP function checkdate.
You can use that in your code like:
if (!isDate($DOB)) {
$error_message = 'Invalid Date';
}
string_explode given string and then pass parts of it to
bool checkdate ( int $month , int $day , int $year )
unfortunately you cannot know if user posted month and day in your format if day is not greater than 12
You can do it like this in PHP:
$date=explode("/",$_POST['DOB']);
if(checkdate ($date[1] ,$date[0] ,$date[2]))
{
echo "valid";
}
else
{
echo "invalid";
}
checkdate will only return true if the three value behind "/" is valid, so if there's no "/" its invalid, same as they put numbers in wrong order.
check manual http://php.net/manual/en/function.checkdate.php
Related
I have created a new date column and it defaults it to 0000-00-00 and I want to check if it has a valid date or all zeros, but none of these codes seem to work for me and I can't figure out why. I know it sees the date, cause when I echo it, it displayed as zeros. How do I check to see if the date column is 0000-00-00? Here is what I tried and none of them have worked.
if (trim($row['date']) == '' || substr($row['date'],0,10) == '0000-00-00') {
// empty date
}
if (strtotime($row['date']) == '0000-00-00'){
// empty date
}
if ($row['date'] == '0000-00-00'){
// empty date
}
EDIT
Looks like it might just be a problem with my godaddy hosting server, I uploaded the files to a free webhosting and solution 3 is working over there. Sorry to waste everyone's time, I do appreciate the quick responses.
You can check the following condition instead of yours...
There strtotime() return false if that not contains a specific date string or for proper check of empty string you can use empty() function and for check that string contains '0000-00-00' like data then you can use strpos() as like the below code:
if(empty(trim($row['date'])) || (strpos($row['date'], '0000-00-00') !== false) || (!strtotime($row['date'])))
{
// empty date
}
If we aren't sure about how the date is being returned, try using date and strtotime together to ensure correct format:
if (date('Y-m-d', strtotime($row['date'])) > '0000-00-00'){
//Valid
}
Simply use empty() with strtotime will check all the empty cases
<?php
$row['date'] = '0000-00-00';
if(empty(strtotime($row['date']))){
// empty date
}
else{
//not empty date
}
If about your 3 condition it should be like below instead of using if ladder use else if and In 2nd condition your are comparing timestamp integer(strtotime will return int seconds) to the string date('0000-00-00') that is in correct
<?php
$row['date'] = '0000-00-00';
if (trim($row['date']) == '' || substr($row['date'],0,10) == '0000-00-00') {
// empty date
}
else if(strtotime($row['date']) == strtotime('0000-00-00')){
// empty date
}
else if ($row['date'] == '0000-00-00'){
// empty date
}
I am a newbie
I got a problem, I want to custom rule in form validation for school year
There is an input box, user have to type like this: 2001/2002 or 2013/2014 or 2017/2018 without any exception
In my controller code:
$this->form_validation->set_rules('nama_tahun_ajaran','nama_tahun_ajaran','required|max_length[9]|callback_valid_name');
function $valid_name($nama_tahun_ajaran){
// RIGHT HERE I'M STILL Have no Idea to makes a rule
}
I hope you understand what I ask
Thanks
You could use a regular expression to match the string, then make a simple comparison to ensure the years are within a year of each other and are in the valid order.
function valid_name($nama_tahun_ajaran = null)
{
// Regex patterns for year and forward slash
$year = '((?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])';
$slash = '(\\/)';
// Does the inputted value matche the regex?
// Checks it's in the form 'year/year'. E.g. '2010/2012'.
if (preg_match_all("/".$year.$slash.$year."/is", $nama_tahun_ajaran, $matches))
{
// Get the years from the string
$first_year = $matches[1][0];
$second_year = $matches[3][0];
// Is the first year one less than the second year?
if (($first_year + 1) == $second_year)
{
return TRUE;
}
}
return FALSE;
}
This will only work with years in the range 1000-2999.
I've been googling a bit, but I can't figure out what keywords to use.
I'm saving the users date of birth, and I want to make sure the format is YYYY-MM-DD.
I'm thinking something like:
if(!ctype_digit(str_replace("-", "", $dob)) || strlen(str_replace("-", "", $dob)) != 8)
{
echo "Incorrect format: date of birth";
}
For this, I need to use strlen() to only replace three - chars. If it's more or less than 3, then echo incorrect format. How do I achieve this? Or is there a better way?
How about using regex?
if ( !preg_match( "/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $dob) )
{
echo "Invalid date.";
}
To find many examples, search for "validating dates" or, in your case, to find php examples, try "php validate date format" -- you'll see most examples are solved with regular expressions, which is your ticket this this sort of thing. Reg Expressions can help you validate dates, email address formats, inputs for passwords that meet minimal requirements (e.g. at least 8 characters, at least one numeric and one capital letter, etc.)
Here's one such example:
if(preg_match('/\d{4}-\d{2}-\d{2}/',$date)){
// good date
}else{
// bad date
}
You should also check that the date is an actual date; not just that it looks like an actual date.
if (!preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/D", $dob))
{
echo 'Invalid date';
}
else
{
list($year, $month, $day) = explode('-', $dob);
if (!checkdate((int) $month, (int) $day, (int) $year))
{
echo 'Invalid date';
}
}
You don't want to accept 1988-06-31 after all.
I have an online form that has a few fields with time data. I store this data into the MySQL data base into a time field, which needs a format hh:mm:ss. If the user inputs the time in this format correctly, then i want to accept the data. I also want to allow users to input the time in standard US time, like 9:30 am or 11:25 pm or 10:27 am etc.
Basically I want to test if the time is in the proper database format first (hh:mm:ss), then if it is not, test if it is in the second accepted format (hh:mm am/pm), and if it is, then I will use the PHP function strtotime() to convert it into the database time format. If it is in neither of these formats, then we display an error message and die.
Does anyone know how to test if the value of a variable matches one of these time formats?
Pseudo PHP code of what I want to do:
<?php
$value = //some time;
if (is_database_time($value)){
// good no problem
}else if (is_usa_time($value)){
$value = strtotime($value);
}else{
die("error incorrect time format, try again.");
}
?>
** EDIT **
Thanks everyone for the help. I used some of the info here to make a function that works perfectly:
<?php
function filter_time($key,$value){
// this section handles the storage of time data
if (preg_match('/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)){
//do nothing
}else if (preg_match('/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i', $value)){
$value = date( 'H:i:s', strtotime($value));
}else{
display_error('incorrect time format in '.$key.' field.');
}
return $value;
}
?>
function verify_time_format()
function verify_time_format ($value) {
$pattern1 = '/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/';
$pattern2 = '/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i';
return preg_match ($pattern1, $value) || preg_match ($pattern2, $value);
}
Returns TRUE for following values:
2:03:32
02:03:32
23:59:59
15:23 AM
15:23 am
09:41 pm
9:41 PM
etc...
Update:
function filter_time ($key, $value) {
$p1 = '/^(0?\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$/';
$p2 = '/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i';
if (preg_match ($p1, $value) || preg_match ($p2, $value))
$res = date ('H:i:s', strtotime ($value));
else
display_error ("incorrect time format in {$key} field.");
return $res;
}
You're already using the strtotime from PHP, and for the values you specified there really is no need to force a specific format.
What you would likely want to test for and ensure, is that the field validates with only digits, the colon, and am or pm as in Wh1T3h4Ck5 answer.
With that in place, your code would likely be similar to the following
<?php
function valid_time($value) {//Wh1T3h4Ck5's function
return preg_match('/^(0?\d|1[0-2]):[0-5]\d\s(am|pm)$/i', $value);
}
$value = //some time;
if (vald_time($value)){
$time_value = strtotime($value);
echo $time_value;
}else{
die("Error incorrect time format, try again.");
}
?>
Though a more elegant solution would to look into using Jquery/Javascript PRIOR to the form being submitted. You can test and warn the user of improper format before submitting to the PHP script. Leave the validation in the PHP script though as well, with other safeguards if needed.
You can use a regular expression to solve the problem pretty easily. For example:
<?php
$databaseTimePattern = '/^(0[0-9])|(1[0-2]):[0-5][0-9]:[0-5][0-9]$/'; //Matches times in the form hh:mm:ss
$usaTimePattern = '/^([1-9]|(1[0-2])):[0-5][0-9] [a|p]m$/'; //Matches times in the form hh:mm am/pm
$value = //some time;
if (preg_match($databaseTimePattern, $value)){
// good no problem
}else if (preg_match($usaTimePattern, $value)){
$value = strtotime($value);
}else{
die("error incorrect time format, try again.");
}
?>
I am in the middle of setting up a basic CMS that allows the client to add articles to their mobile app. The CMS is coded in PHP and will use JSON to deliver the content to the mobile app.
Now my problem is there is an option to publish the article at a certain date, so I want to validate the date to check it is valid.
So to test possibilites I made a small script. I am using strtotime() to check the date is valid, my script is:
<?php
$date[] = '2011-31-01';
$date[] = '2011-02-31';
foreach($date as $str) {
if(strtotime($str) == false) {
$result[] = '<p>[' . $str . '] Resulted in an <span style="color: red;">Error.</span></p>';
} else {
$result[] = '<p>[' . $str . '] Resulted in <span style="color: green;">Success.</span></p>';
}
}
foreach($result as $return) {
echo $return;
}
?>
Now my problem is the date 2011-02-31 which is 31st February 2011 is returning as valid, when obviously it isn't. So my question is why does it do this? and is there a better method to check that the date is valid and exists?
Thanks in advance.
checkdate(); Validates a Gregorian date. Returns TRUE if the date given is valid; otherwise returns FALSE.
if(checkdate(2, 31, 2011)){
echo "Yeah";
} else {echo "nah";}
It returns false!
That's the way to go.
Unless you have one (or a small set) fixed format for your date string it will be hard to get an acceptable result. In case you know the format, you can either parse the string directly yourself (and test it afterwards with checkdate), or you use strptime to try parsing against known formats until you get a valid result.
If you don’t know the format, and you have to use strtotime, then you are required to accept that strtotime will try parsing the date string in the best possible way. This may lead to different dates than it was expected to be.