In a flex app I’m building, I have two dates a user needs to put in for an event. I needed a way to make sure the end date was not before the start date. Now, I know this is pretty common sense for a user to be able to do this but you never can tell. At any rate, I needed a custom validator for this to take two dates and compare them to make sure that the end date was not before the start date when the validations occurred.

After doing some research on the Google to find ways to get me started, I came up with the following as the fruit of my labor. Please note that the comments give reference to the articles that I utilized in building this validtor.

////////////////////////////////////////////////////////////////////////////////
// Based loosley on examples found in the following places:
//
// How to Validate a Date Range in Flex:
// (Basic idea for comparing a given date to a pre-defined range. This object did not meet my needs exactly so I used this as a starting point.)
// http://www.davidortinau.com/blog/how_to_validate_a_date_range_in_flex/
//
//
// How to Compare Two Dates in ActionScript 3:
// (Shows comparing dates as Numbers)
// http://userflex.wordpress.com/2008/09/11/as3-date-compare/
//
// Flex: How do you validate 2 password fields to make sure they match?
// (Shows how to get two fields to validate, makes use of the getValueFromSource() method.)
// http://stackoverflow.com/questions/508696/flex-how-do-you-validate-2-password-fields-to-make-sure-they-match
//
// Actionscript 3 - Fastest way to parse yyyy-mm-dd hh:mm:ss to a Date object?
// (Ran into trouble on getting my dates to parse correctly given the yyyy-mm-dd format, this article pointed to a solution)
// http://stackoverflow.com/questions/3163/actionscript-3-fastest-way-to-parse-yyyy-mm-dd-hhmmss-to-a-date-object
////////////////////////////////////////////////////////////////////////////////
package com.wg.utility
{
	import mx.validators.DateValidator;
	import mx.validators.ValidationResult;

	public class StartEndDateValidation extends DateValidator
	{
		private var _startDateSource:Object;
		private var _startDateProperty:String;

		public function StartEndDateValidation()
		{
			super();
		}

		public function set StartDateSource(value:Object): void
		{
			_startDateSource = value;
		}

		public function set StartDateProperty(value:String):void
		{
			_startDateProperty = value;
		}

		override protected function doValidation(value:Object):Array {
			// Create an array to return validator results
			var validatorResults:Array = new Array(); 

			// Call base doValidation() this assures EndDate (source) is correctly validated as a date.
			validatorResults = super.doValidation(value.enddate);

			// Return if validation has errors.
			if (validatorResults.length > 0) {
				return validatorResults;
			}

			if (String(value).length == 0) {
				return validatorResults;
			}

			// Use castDate to properly cast the date's text property into a Date object.
			var startDate:Date = castDate(value.startdate);
			var endDate:Date = castDate(value.enddate);
			var startDateTimeStamp:Number = startDate.getTime();
			var endDateTimeStamp:Number = endDate.getTime();

			if (endDateTimeStamp < startDateTimeStamp) {
				validatorResults.push(new ValidationResult(true, null, "Invalid Date Range", "End Date is before Start Date"));
				return validatorResults;
			}

			return validatorResults;

		}

		override protected function getValueFromSource():Object
		{
			var value:Object = {};
			value.enddate = super.getValueFromSource();

			if (_startDateSource && _startDateProperty) {
				value.startdate = _startDateSource[_startDateProperty];

			}
			return value;
		}

		private function castDate(dateString:String):Date {
		    if ( dateString == null )
		        return null;
		    if ( dateString.length != 10 && dateString.length != 19)
		        return null;

		    dateString = dateString.replace("-", "/");

		    return new Date(Date.parse( dateString ));
		}

	}
}

To implement this in my MXML, I needed to put in the following code. In my component declaration, I needed the following namespace so I could reference to it as a validator.



...

The fields I wanted to validate are illustrated in the following snippet below:

...

	


	

...

Make note in the above code that the format string for each field is "YYYY-MM-DD." I did this for ease of entry into my database. However, this tripped me up when trying to get an actual date object parsed in so I could use it for comparison. That is the reason for the function castDate() in the validator.

The validator array grouping I used for the component listed below shows how the validator references both the start date and the end date. The way this validator works is the validation is bound to the endDate field and the startDate is referenced by the attributes "StartDateSource" and "StartDateProperty." In addition, the endDate is also validated as a valid date by the standard DateValidator method. For validating the startDate field, I used a standard DateValidator reference.


    
    

Finally, the validation is executed (normally via a button click) with the following code:

	var results:Array = Validator.validateAll(validators);
	// if any of the fields were not valid
	if (results.length > 0) {
		return;
	}