Flex中利用正则表达式对数据进行验证的例子

By Minidxer | August 1, 2008

在前面Flex中利用RegExp类正则表达式功能对用户Flash Player版本信息进行解析的例子中,我们了解了Flex中如何利用RegExp类正则表达式功能,对用户Flash Player版本信息进行解析。接下来的例子演示了Flex中如何利用正则表达式对数据进行验证。

让我们先来看一下Demo可以右键View Source或点击这里察看源代码):


下面是完整实现代码(或点击这里察看):

Download: main.mxml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
  3.         layout="vertical"
  4.         verticalAlign="middle"
  5.         backgroundColor="white">
  6.  
  7.     <mx:Script>
  8.         <![CDATA[
  9.             private const postalcode_regex:RegExp = /^[A-Z][0-9][A-Z] [0-9][A-Z][0-9]$/i;
  10.  
  11.             private function validatePostalCode(evt:Event):void {
  12.                 if (postalcode_regex.test(ti1text)) {
  13.                     ti1.errorString = null;
  14.                 } else {
  15.                     ti1.errorString = postalCode_errorString;
  16.                 }
  17.             }
  18.         ]]>
  19.     </mx:Script>
  20.  
  21.     <mx:String id="ti1text">{ti1.text}</mx:String>
  22.     <mx:String id="postalCode_errorString">
  23.         <![CDATA[Please enter a valid postal code in "L9L 9L9" format.]]>
  24.     </mx:String>
  25.  
  26.     <mx:Form>
  27.         <mx:FormItem label="Postal Code:" required="true">
  28.             <mx:TextInput id="ti1"
  29.                     maxChars="7"
  30.                     restrict="A-Z 0-9"
  31.                     change="validatePostalCode(event)" />
  32.         </mx:FormItem>
  33.     </mx:Form>
  34.  
  35. </mx:Application>
代码:Peter deHaan 翻译/整理/编译:minidxer

Topics: Flex | Tags: , ,

Search Posts

Archives

Sponsored Ads