Home > Adobe Flex/Air > Simple login form with Flex and XML as database

Simple login form with Flex and XML as database

I want to create a simple login form to learn how to work with Validation and XML database (based on E4X) in Flex.

login

Fist we need an XML file which contains our login information, i call it [data.xml]. We have two [user] elements (but you can add as much as you want), each element contains one user’s data includes user id and password. This file must be put at the same folder as the compiled source file. To learn more about XML, visit the W3Schools’ XML Tutorial at http://w3schools.com/xml/.

<?xml version=”1.0″ encoding=”utf-8″ ?>
   <data>
      <user>
         <userid>UI0001</userid>
         <password>123</password>
         <username>Nguyen Van A</username>
      </user>
      <user>
         <userid>UI0002</userid>
         <password>456</password>
         <username>Tran Van B</username>
      </user>
</data>

The next step is to create an mxml file called login.mxml. This file is used to control login form’s layout and handle event. The controls do not have anything paticularly complex. We start with a panel , inside it we add two Textinput controls for user id, password and a button to submit data. Finally, we have two StringValidators used for [Required], [MinLength], [MaxLength] validation.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”  layout=”absolute”>
   <!-- Validation -->
   <mx:StringValidator id=”useridValidator” required=”true”
          minLength=”6” maxLength=”25″
          source=”{userid}” property=”text”
          trigger=”{btnLogin}” triggerEvent=”click” />

   <mx:StringValidator id=”passwordValidator” required=”true”
          minLength=”6” maxLength=”25″
          source=”{password}” property=”text”
          trigger=”{btnLogin}” triggerEvent=”click” />

   <!-- Main form controls -->
   <mx:Panel title=”Login Form” horizontalCenter=”0″ verticalCenter=”0″>
      <mx:Form>
         <mx:FormItem label=”User ID”>
            <mx:TextInput id=”userid” />
         </mx:FormItem>
         <mx:FormItem label=”Password”>
            <mx:TextInput id=”password” displayAsPassword=”true” />
         </mx:FormItem>
         <mx:FormItem>
            <mx:Button id=”btnLogin” label=”Login”  />
         </mx:FormItem>
      </mx:Form>
   </mx:Panel>
</mx:Application>

We finished the layout. Now we’re going to start building the action script to hanle screen related events. At the initialization stage, we’ll add two validators into an array for later validation. (Remember to add creationComplete=”init()” into <mx:Application>)

[Bindable]
private var validatorArr:Array;

/**
* Initialization method
*/
public function init():void {
   // Add validators to array for validating all at one time
   validatorArr = new Array();
   validatorArr.push(useridValidator);
   validatorArr.push(passwordValidator);
}

then when user click on [Login] button we must call the inserted validators to validate user’s inputted data. If the result is valid, start loading data from XML and loop through it to find if the inputted data exist.

/**
* User's information checking
* based on the inputted data
*/
public function loginCheck():void  {
   // Starting to validate
   var errorArr:Array = Validator.validateAll(validatorArr)
   // if the error array contain any data, =&gt; error
   var isValid:Boolean = errorArr.length == 0;

   if (isValid) {
      // Load user data
      doLogin();
   }
}

private function doLogin():void {
   // Point to the data file's path
   var request:URLRequest = new URLRequest("data.xml");

   loader = new URLLoader();
   try {
      loader.load(request);
   } catch (error:SecurityError) {
      trace("A SecurityError has occurred.");
   }

   // If error, go to errorHandler function
   loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
   // once the load action was complated, go to loaderCompleteHandler() for
   // checking user information
   loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
}

private function loaderCompleteHandler(event:Event):void {
   var logged:Boolean = false;
   try {
      // Convert data into E4X class for easy access to elements
      externalXML = new XML(loader.data);

      // Loop through the user list to check
      // if the inputted user id and password are valid
      for each (var user:XML in externalXML.elements()) {
         if (user.userid == userid.text && user.password == password.text) {
            // user has an valid account
            logged = true;
            // Don't need to continue
            break;
         }
      }
      if (logged) {
         Alert.show('Congratulation, you logged in!', 'Information');
         // you could redirect user to main form here
      } else {
         Alert.show('User ID or Password is not correct, please try again!', 'Error');
      }

   } catch (e:TypeError) {
      trace("Could not parse the XML file.");
   }
}
private function errorHandler(e:IOErrorEvent):void {
   Alert.show("Had problem loading the XML File.");
}

The final step is to add click event for Login button [click="loginCheck()"].

Reference resources

Working with XML in Flex 3 and Java-part1
URLLoader

Hope this help!

※All comments or improve ideas will always be appreciated.

In the next article, I’ll show you how to make login form using Flex and AMFPHP (a remote object access method)

About these ads
Categories: Adobe Flex/Air Tags:
  1. Sam
    January 5, 2011 at 12:06 AM | #1

    Very useful – thanks! Just to note you omitted the
    private var loader:URLLoader;
    private var externalXML:XML;

    which are required for the last block of code but other than that works great!

  2. gautam
    May 9, 2012 at 5:03 PM | #2

    Thanks very useful :)

  3. Islam
    May 22, 2012 at 8:52 PM | #3

    Thanks very much that`s work.

  1. No trackbacks yet.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: