1 Reply Latest reply on Jan 5, 2008 5:07 PM by VarioPegged

    Validaing a string


      I am new to Flex and I want to validate a InputText (country) in a XMLListCollection of a countries.
      I use the autocomplete component from Adobe, that is working fine, but if I type a text that is different from a country name I want to show this (validate this). I don't know how to use a function (specific to e4x ) to test if country.text is in lCountries.
      Below, is the variable for the countries.

      <mx:XML id="lCountries"
      <name>United States</name>

      Thanks in advance,
        • 1. Validaing a string
          VarioPegged Level 2
          I've not used the autocomplete component, but I imagine it's just a special type of TextInput component, right?

          With that in mind, here is a complete solution I put together for you... what can I say, I've been in a helping mood here in the past week or so. Oh, and that community service thing...;-)

          This example is based on the XML in your post.

          Add this function to an <mx:Script> block in your application:

          private function validateEntry(event:Event):void
          var textInput:String = event.currentTarget.text;
          var inputLength:int = event.currentTarget.text.length;
          var countryNames:XMLList = lCountries.Country.name;
          var errString:String = "";
          var matchedChar:int = 0;

          event.currentTarget.errorString = "";

          for (var a:int = 0; a < countryNames.length(); a++)
          for (var b:int = 0; b < inputLength; b++)
          if (textInput.charAt(b).toLowerCase() == countryNames[a].charAt(b).toLowerCase())
          if (matchedChar == inputLength)
          errString = "";
          errString = "Invalid Country";
          event.currentTarget.errorString = errString;

          Then add the event attribute change="validateEntry(event)" to the autocomplete component. Here's a sample for a regular text input:

          <mx:TextInput id="countryInput" change="validateEntry(event)" />

          Note that the logic doesn't check for trailing spaces, so if there are any spaces after the country name it'll throw an invalid event even though it'll appear like the user has input the correct name.