<

Date validation using regular expression in perl

Published on
13,110 Points
6,610 Views
Last Modified:
Approved
Whatever be the reason, if you are working on web development side,  you will need day-today validation codes like email validation, date validation , IP address validation, phone validation on any of the edit page or say at the time of registration (minimum).

You can do these by using JavaScript (client-side) or through any language like PHP, Perl etc. (Back end side). As right now I am working on Perl, so my validation codes would be in Perl only.  

Date Validation using Regular expression in Perl
Date consists of three main things i.e. Date of the month, month of the year and year itself and one more thing that is required is the separator (/ or –  ). You may choose any other separator, no issues. So, after combining all these things we will get date like MM/DD/YYYY or DD/MM/YYYY or YYYY/MM/DD (you can use – or anything instead of /, that I used here). DD being the date, MM being the month and YYYY being the year.

So , to  accomplish the task, we have to check that:
a.     DD of the date should be between 1 and 31 ,
b.    MM should be between 1 and 12
c.   YYYY should be from 1900 and till date (Instead of today’s date you can put  boundary of any date)
d.   If MM is 02 i.e. February, then DD should be between 1 and 28 and if its leap year then DD can extend up to 29.
So, here is the magic of line which will do all validation itself, using regular expression:

It would match dd-mm-yyyy or dd/mm/yyyy pattern for rest of the patterns you have to change the code little bit.
 
$pattern='^(0[1-9]|[12][0-9]|3[01])[- /](0[1-9]|1[012])[- /]((19|20)\d\d)$';

Open in new window



If date is  single digit only, put 0 in-front of it, then only it will work.

Explanation
First parenthesis is for date which will allow you to put only 01-31 then second parenthesis is for month which will allow you to enter from 01-12 only.
Last parenthesis is for Year which will take values from 1900 to 2099 (at max but you can restrict it to today’s date by using localtime())


 
#!C:/strawberry/perl/bin/perl.exe     # path to my perl compiler, change it with yours ex: #!/usr/bin/perl
#########################################
# Author: Sanjeev Kumar Jaiswal
# Date: October 2010
# Purpose: Date Validation in any format you wish.
# ex: dd-mm-yyyy or dd/mm/yyyy
########################################
use strict;
use warnings;
my @today = localtime();  #get current system time
my $year = $today[5]+1900;
my $month = $today[4]+1;
my $date = $today[3];
print "Todays is ", scalar localtime, "\n";
print "This program is to check the validation of date\n From 1900 to till now i.e.", $today[5]+1900 ," only\n";
print "Please enter the date in specified format i.e. DD/MM/YYYY or DD-MM-YYYY\n";
my $mydate=<STDIN>;   # to get the input from keyboard
chomp($mydate);    # have to remove \n from the last that came after hitting enter
# Pattern for date validation
#dd-mm-yyyy  from 1900-2099 (Year)
my $pattern='(0[1-9]|[12][0-9]|3[01])[- /](0[1-9]|1[012])[- /]((19|20)\d\d)';  
# If it matches the pattern then
if($mydate=~ m/$pattern/){
     if($2==02 && $1>29){
     print "February can't be of more than 28 or 29 days";
     exit;
     }
     if(!($3 % 4 == 0 && ($3 % 100 != 0 || $3 % 400 == 0)) && $2==2 && $1==29){
     print "Its not a leap year, so please type the date between 1 and 28";
     exit;	
     }
     if($1 == 31 and ($2 == 4 or $2 == 6 or $2 == 9 or $2 == 11)){
     print "This month only allow upto 30 as th date input";
     exit;
     } 
     if($3>$year){
     print "The provided date is the future date i guess. its year should be less or equal to $year\n"; 
     exit;             
     }
     if($3 >= $year){
        if($2>$month){
	print "You have entered $2 at Month's place which is ahead of $month";
	exit;
	 }
	else{
	     if($1>$date){
	     print "You have entered $1 at Date's place which is ahead of $date";
	     exit;
             }
	}
    }
 print "You have entered $mydate, which is correct according to us";
}
else{
print "$mydate does not follow the pattern DD/MM/YYYY or DD-MM-YYYY  or \n you have entered some junk date like\n 1. 32 as date or \n 2. 13 as month or\n 3. 3100 as year";
}
############# End Program ################

Open in new window


Quote
Main part was only that Regular Expression(RegEx) which solves our problem within a line. You can use that line in any language like PHP,JavaScript, ASP.NET etc.


Source: Alien Coders Forum
0
Comment
  • 3
  • 2
5 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
>>  So, here is the magic of line which will do all validation itself, using regular expression:

Not that you *could* do it with regex, but I don't see where option "d" is covered by that pattern. The above statement is a bit misleading. Actually, the title of this article itself is a bit misleading. The title implies that regex itself can be used to validate dates. While I have seen very intricate patterns which did a fairly decent job, using regex to validate dates is a messy business. I think at best, you could use them to validate the proper structure of a date (e.g. DD/MM/YYYY vs DD-MM-YYY), but with regard to validating whether or not a date is valid, that should be left up to complete logic, as your post demonstrates.
0
 
LVL 6

Author Comment

by:Sanjeev Jaiswal
Well i could use \d but \d means 0-9 and i have condition like if it start from 0 then next digit should be from 1-9, if date starts from 1 or 2 it should go from 10-29 only and if date starts from 3 then you can enter only 30 and 31 .
That is why i have used (0[1-9]|[12][0-9]|3[01]) for date dd patter instead of blindly using \d.
And it would reduce programmers time too.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
Use of \d vs. [0-9] is not what I'm referring to. The only thing your pattern is buying you above is that you are validating a particular structure for your incoming string. You are still having to validate the parts separately (e.g. validating that a date in February does not exceed 28 or does not exceed 29 in a leap year). What I am saying is that full date validation via a regex results in complex patterns which are difficult to read. Given what you have posted above, I argue that you are not validating the date itself, merely its structure, and even then it's a loose validation.
0
 
LVL 6

Author Comment

by:Sanjeev Jaiswal
Yes you are right. Thanks for your review.
I just tried to keep it as simple as i can. Otherwise validating i na single would make it more complex and less preferable.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
I see time and time again posts for people asking how to validate dates and other strange values that would be better serviced by full logic, yet people still want to use Regex to do the validation. I'm guessing it's because they don't fully understand what Regex is or is useful for. I think the article is well intentioned and useful to those looking for that sort of thing. Keep at it  :)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Join & Write a Comment

Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month