Sure fire method to validate the Date field Server Side

Regex expressions are not the perfect solution to identifying valid dates. Neither does parsing a String date using the DateFormat guarantee a correct date since the year, month and day tend to roll over. And hence Date ParseException only ensures that your date is in the correct format.
Here is a quick and sure fire method to verify that the date you entered is exactly what you intended to in the first place. (I have used a JSF backing bean snippet):

		String dateParam = ...
		DateFormat dateFormat = null;
		Date date = null;
		boolean flag = true;
		try {
			dateFormat = new SimpleDateFormat("dd/MM/yy");
			date = dateFormat.parse(dateParam);
			System.out.println(date.toString());
			if (!dateFormat.format(date).equals(dateParam)) {
				msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
						"The date that you provided is invalid ", null);
				context.addMessage("dateId", msg);
				flag = false;
			}
		} catch (ParseException e) {
			msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					"Please enter date in dd/MM/yy format ", null);
			context.addMessage("dateId", msg);
			flag = false;
		}
		if (flag == false) {
			return null; // redirect to original page to display error message
		}

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: