How to Validate a Date Range in Flex

I had the need to validate a date based on a range of allowed dates, and I couldn’t find this validation control anywhere for Flex. The reason is probably because it’s just so easy to write.

The solution is to write a custom validator that extends DateValidator, pass in the start and end dates, and then perform the validation. This way I can benefit from the nice inline validation Flex gives us.

The actual validation code to compare dates is based on the Date.parse() which you can see in the class code.

The class: DateRangeValidator.as

In my form I’ve been using a form validator that checks all the validation controls in the array and when it’s all good enables the form button. The Flex code for my form looks basically like this:

  1. <mx:Form>
  2. ... other fields ...
  3. <mx:FormItem label="Date of Birth" required="true" labelStyleName="fieldLabel">
  4. <mx:DateField disabledRanges="{[ {rangeStart: new Date(1988,0,1), rangeEnd: new Date(2025,11,30)} ]}" id="dateOfBirth" yearNavigationEnabled="true" editable="true" formatString="MM/DD/YYYY" minYear="1900" maxYear="1988" change="this.formValidator.validateForm(event);"/>
  5. </mx:FormItem>
  6. ... other fields ...
  7. <mx:FormItem horizontalAlign="right" width="349">
  8. <mx:Button id="btnSubmit" click="submit()" label="NEXT"
  9. enabled="{this.formValidator.formIsValid}" />
  10. </mx:FormItem>
  11. </mx:Form>

Then I have my array of validators:

  1. <mx:Array id="validators">
  2. ... some validators ...
  3. <validators:DateRangeValidator id="valDateRange" source="{dateOfBirth}" property="text" StartDate="{new Date(1900,0,1)}" EndDate="{new Date(1988,0,1)}" required="true"/>
  4. </mx:Array>

And the custom form validator that checks all fields to make sure it’s all valid before enabling the button. For more info on this, check out this article and code from Joel Hooks.

  1. <validators:FormValidator id="formValidator" validators="{this.validators}"/>

And that’s it. I hope this saves someone a little time. If you have any comments or improvements, please let me know.


Categories: GeneralFlexPermalink
blog comments powered by Disqus