Calculate Ages and Verify Date using Regular Expression in Javascript

According to Goyvaerts and Levithan in their book, Regular Expressions Cookbook, “Regular expression is a specific kind of text pattern that you can use with many modern applications and programming languages.”

We can use regular expression to verify many things in our applications, such as credit card numbers, email addresses, social security numbers, zip codes, dates, etc.

I was assigned to create a web-page that calculated employees’ ages by filling out the date of birth employees. As we know, date has its own pattern that we cannot violate it in our application. If someone input the date incorrectly, it will damage our data in database. Therefore, we have to verify all data before insert it in to the database.

incorrect

Figure 1: Date is typed incorrectly

Figure 1 shows us a message box that appears after someone typing a wrong date pattern. We know that there is 12 months in a year and 30 days in even months, and 31 days in odd months.

regex

Figure 2: Regular expression pattern

Figure 2 shows us the regular expression pattern that I used to verify the date. However, the pattern did not cover the date of February in the Leap Year. So, I created a little bit javascript code to cover that issue. Please see Figure 3.

leapyear

Figure 3: Javascript code for leap year

So, if someone type 02-29-1987, the message box will pop up like in the Figure 4.

feb1987

Figure 4: February 1987

If someone type 02-29-1988, which is a correct date pattern, the application will calculate the ages automatically. Please see figure 5.

ages

Figure 5: Ages has been calculated

Categories: Portfolio | Tags: , , , , , | Leave a comment

Post navigation

Leave a comment

Blog at WordPress.com.