C++ program for date validation

In this blog, we will create a program to date validation in C++.

What is Date Validation?

The project asks the user to enter a date in mm/dd/yyyy format. Based on the information provided, the program must determine whether the date is valid or invalid and then display an answer to that.

Algorithm for the respective code

For a date to be valid, it must occur somewhere in time. To verify the date, we check Day Month Year.

First, we check the year. The valid range set in the program is between 1000 and 3000. If it is not in the range, the date is invalid.

Second, validation is done for the month, which must be between 1 and 12.

Finally, the days are checked according to the months. The day’s value can be between 1 and 28,29,30,31.

Example: Entry: 12 02 1999

Output: The string is valid.

C++ code for the respective program

#include<iostream>
using namespace std;

int main(){
  
  int day,month,year;
  
  cout<<"Enter the date (Day Month Year) : \n";
  
  cin>>day>>month>>year;
  
  if(1000 <= year <= 3000)
       {
         if((month==1 || month==3 || month==5|| month==7|| month==8||month==10||month==12) && day>0 && day<=31)
         cout<<"It is valid";
         else 
     if(month==4 || month==6 || month==9|| month==11 && day>0 && day<=30)
            cout<<"It is Valid";
         else
            if(month==2)
               {
               if((year%400==0 || (year%100!=0 && year%4==0)) && day>0 && day<=29)
                 cout<<"It is Valide";
               else if(day>0 && day<=28)
                  cout<<"It is Valid";
               else
                  cout<<"It is Invalid";
               }
         else
               cout<<"It is Invalid";
      }
    else
        cout<<"It is Invalid";
  
  return 0;
}

Output of the above code

*When date is valid

*When date is not valid

Explanation of the code

  • The user enters a date to check. The value is inside the variables day, month, and year.
  • Check if the year is between 1000 and 3000.
  • If the year is valid then the month is checked, the month must be between 1 and 12.
  • Finally, the day is the inspection. Days are checked by month January, March, May, July, August, October, and December will have 31 days and all others will have 30 days except February. For February we need to check the year first, if it is a multiple of 4 then the month will have 29 days, otherwise, it will have 28 days.
  • If the date passes all of the above cases, it is valid.