Flex Tip - Trigger validation when submitting form

I just noticed a common pattern in the way I do validation, so I thought I would share. (in case you didn't know this already)

The validators are great at telling the user what is required or failing validation as the tab through the form. However they don't actually block the user from submitting the invalid form. But there is a simple way to do this with the validators.

1. Group all of the validators into an MX:ARRAY tag, and give it a unique id. - I usually use "validators"

<mx:Array id="validators">
   <mx:StringValidator source="{abbreviations}" property="text" required="true"/>
   <mx:StringValidator source="{subcode}" property="text" required="true"/>
   <mx:StringValidator source="{name}" property="text" required="true"/>
   <mx:StringValidator source="{letterType}" property="text" required="true"/>
   <mx:StringValidator   source="{scheduleType}" property="text" required="true"/>
</mx:Array>

Since the validators are now all grouped in an Array, you can call the Validator.validateAll() function to check them all at once.

2. Use this if statement in the click event of your form submit button to check the validators before submitting. You can also add this if check inside your doSave() method too. whichever you prefer.

if( Validator.validateAll(validators).length==0 ){ doSave() }

<mx:Button
   label="Save"
   click="if( Validator.validateAll(validators).length==0 ){ doSave() }"/>

Comments
Oliver Merk's Gravatar Nice way to do this. More readable than passing the array elements to the function directly e.g. Validator.validateAll([ myVal1, myVal2... ])

Cheers,
Oliver
# Posted By Oliver Merk | 10/11/07 4:30 PM
Webdesign's Gravatar Many thanks for the interesting informations
# Posted By Webdesign | 2/5/08 3:11 PM
Andychou's Gravatar Need 3 Flex engineers in New York City:
1. You have to be living in New York City for now.
2. Work part time or full time with us.
3. Good at Adobe Flex technology.
4. Please contact us for other requirement and details.

Busycode Inc. is a top Adobe Flex shop who develops Flex/AIR applications for clients.
For more info, please visit http://www.busycode.com
# Posted By Andychou | 4/17/08 5:33 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.001.