注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Flex 技术博客

醉里挑灯看剑,梦回吹角连营

 
 
 

日志

 
 

一个文件扩展名验证器(File Extension Validator)  

2008-09-19 13:21:01|  分类: Flex 组件 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

一个文件扩展名验证器(File Extension Validator) - 阿蔡 - Flex 技术博客

在实际开发过程中,我们经常需要一些特殊的validator,flex自己提供了一些常用的,如StringValidator, DateValidator, NumberValidator, EmailValidator以及ZipCodeValidator等等,这些validator的具体用法这里不做描述,在这里我要介绍一个自己写的validator:FileExtensionValidator。功能很简单,就是验证一个文件名的后缀扩展名是否是我们所需要的,这个在文件上传之前选择文件的时候会用到,它继承了StringValidator,实际上就是对一个字符串进行判断。用法也很简单,不过这确实一个如何自己写validator的很好例子。具体代码如下:

 /**

 * Revision History

 *

 * Date           Programmer         Notes

 * ------------   ----------------   --------------------------------------------

 * Sep 19, 2008     Weimin Cai                   initial

 */

package com.cwmlib.components

{

      import mx.validators.StringValidator;

      import mx.validators.ValidationResult;

     

      public class FileExtensionValidator extends StringValidator

      {

            /**

             *    This validator can validate wheter the file extension is match or not

             * @fileExtends:Array , can match multiple files extension

             * @fileExtend:String , can match one type file

             */

            public var fileExtends:Array = [];

            public var fileExtend:String = ".*";           

           

            private var noExtendsError:String = "The file extend name is not match required";

            public var notMatchTypeError:String = "";

            public var notMatchTypesError:String="";

           

            public function FileExtensionValidator()

            {

                  super();

            }

           

            override protected function doValidation(value:Object):Array{

                  var results:Array = super.doValidation(value);

                  var val:String = value ? String(value):"";

                  if(results.length > 0 || val.length == 0)return results;

                  else{

                        return FileExtensionValidator.validateFileExtend(this,value,null);

                  }

            }

           

            public static function validateFileExtend(validator:FileExtensionValidator,

                              value:Object,baseField:String=null):Array{

                  var results:Array = [];

                  var val:String = value != null ? String(value) : "";

                  var index:int = val.lastIndexOf(".");

                  if(index < 0){

                        results.push(new ValidationResult(

                              true, baseField, "noExtend",

                              validator.noExtendsError));

                        return results;

                  }

                  var extendName:String = val.slice(index);

                  if(validator.fileExtends.length == 0){

                        if(validator.fileExtend != ".*" && extendName != validator.fileExtend){

                              results.push(new ValidationResult(true,baseField,"notMatchExtend",

                                    validator.notMatchTypeError!=""?validator.notMatchTypeError:"The file extension should be "+validator.fileExtend));

                              return results;

                        }

                  }else{

                        if(validator.fileExtends.indexOf(extendName) < 0){

                              results.push(new ValidationResult(true,baseField,"notMatchExtend",

                                    validator.notMatchTypesError!=""?validator.notMatchTypesError:"The file extension should be "+validator.fileExtends.toString()));

                              return results;

                        }

                  }

                  return results;

            }          

      }

}

//FileExtensionApp.mxml

//---------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"

      xmlns:cwmlib="com.cwmlib.components.*">

      <mx:Script>

            <![CDATA[

                  import mx.events.ValidationResultEvent;

                  import flash.net.*;

 

                  private var file:FileReference;

                 

                  private function handleValid(event:ValidationResultEvent):void {

                        if(event.type == ValidationResultEvent.VALID){

                              uploadBtn.enabled = true;

                        }else{

                              uploadBtn.enabled = false;

                        }

                  }

                 

                  //------------------- file browse ---------------------------------------------

                  private function browseFile():void {

                        file = new FileReference();

                    file.addEventListener(Event.SELECT, selectHandler,false,0,true);

                      file.addEventListener(Event.CANCEL, cancelHandler,false,0,true);

                      file.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler,false,0,true);

                      file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler,false,0,true);

                      file.addEventListener(Event.OPEN, openHandler,false,0,true);

                      file.addEventListener(ProgressEvent.PROGRESS, progressHandler,false,0,true);

                      file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler,false,0,true);

                        file.addEventListener(Event.COMPLETE,onComplete,false,0,true);

//                      uploadFileName.text = "";

                        file.browse(getTypes());

                }

                private function selectHandler(event:Event):void {

                        uploadFileName.text = file.name;

                }          

                private function cancelHandler(event:Event):void {

            }               

                private function httpStatusHandler(event:HTTPStatusEvent):void {

                }           

                private function ioErrorHandler(event:IOErrorEvent):void {

                }

                private function openHandler(event:Event):void {

                }      

                private function progressHandler(event:ProgressEvent):void {

                }      

                private function securityErrorHandler(event:SecurityErrorEvent):void {

                }                 

                private function onComplete(event:Event):void {

                }

                private function getTypes():Array {

                     var allTypes:Array = new Array(getAllTypeFilter(),getDocTypeFilter(), getPdfTypeFilter(),getZipTypeFilter());

                     return allTypes;

                }

                private function getAllTypeFilter():FileFilter{

                     return new FileFilter("All Files(*.*)","*.*");

                }    

                private function getDocTypeFilter():FileFilter{

                     return new FileFilter("Office Files(*.xls,*.doc)","*.xls;*.doc");

                }

                private function getPdfTypeFilter():FileFilter{

                     return new FileFilter("Pdf Files(*.pdf)","*.pdf");

                }

                private function getZipTypeFilter():FileFilter{

                     return new FileFilter("Zip Files(*.zip)","*.zip");

                }

                //~------------------- file browse ---------------------------------------------

                 

            ]]>

      </mx:Script>

      <cwmlib:FileExtensionValidator fileExtends="['.xls','.pdf','.doc','.zip']" required="true"

            source="{uploadFileName}" property="text" valid="handleValid(event)" invalid="handleValid(event)"

            trigger="{uploadFileName}" triggerEvent="updateComplete"/>

      <mx:Spacer height="50"/>

      <mx:HBox width="100%">

            <mx:Label text="Select File:" height="40"/>

            <mx:TextInput id="uploadFileName" text="" editable="false" width="200"/>

            <mx:Button id="browseBtn" label="Browse" click="browseFile()"/>

            <mx:Spacer width="20"/>

            <mx:Button id="uploadBtn" label="Upload" />    

      </mx:HBox> 

</mx:Application>

 源码下载和演示地址:http://www.box.net/shared/z4sn2r2num

swf文件可以直接打开演示,也可下载后在本地打开,需要flash player 9.0

  评论这张
 
阅读(12542)| 评论(6)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017