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

    Validaing a string

    pchris1977 Level 1

      Hi,
      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"
      <Countries>
      <Country>
      <name>United States</name>
      <capital>Washington</capital>
      </Country>
      <Country>
      <name>Romania</name>
      <capital>Bucharest</capital>
      </Country>
      <Country>
      <name>France</name>
      <capital>Paris</capital>
      </Country>
      </Countries>
      </mx:XML>


      Thanks in advance,
      Cristy
        • 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())
          {
          matchedChar++;
          }
          }
          }
          if (matchedChar == inputLength)
          {
          errString = "";
          }
          else
          {
          errString = "Invalid Country";
          }
          event.currentTarget.errorString = errString;
          event.currentTarget.drawFocus(true);
          }

          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.

          TS