在刚才的例子上改进后的代码,加上了验证码。
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="initApp()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
//验证登陆
private function loginHandle():void
{
if(txtUsername.text==""||txtPassword.text==""){
Alert.show("请输入用户名和密码!");
}else{
if(txtUsername.text=="admin"&&txtPassword.text=="123"
&&txtCheckCode.text.toLowerCase()== lblCheckCode.text.toLowerCase()){
Alert.show("登陆成功!");
}else{
if(txtCheckCode.text.toLowerCase()!= lblCheckCode.text.toLowerCase()){
Alert.show("验证码错误!");
lblCheckCode.text=GrearateCheckCode();
}else{
Alert.show("用户名和密码错误!");
}
}
}
}
//重置表单数据
private function resetHandle():void
{
txtUsername.text="";
txtPassword.text="";
}
//该函数是应用程序(Application)在初始化 的时候就执行。
private function initApp():void{
//显示验证码
lblCheckCode.text=GrearateCheckCode();
}
private function GrearateCheckCode():String{
//定义变量
var ran:Number;//0-1的随机数
var number:Number;//是ran的10000倍的数
var code:String;//生成单个的字母
var checkCode:String="";//返回的验证码
//生成四个随机数(转换为字符)
for(var i:int=0;i<4;i++){
ran=Math.random();
number=Math.round(ran*10000);
if(number%2==0){
//通过fromCharCode()是用ASCII码来给字符串赋值,返回一个字母
code=String.fromCharCode(48+(number%10));
}
else{
code=String.fromCharCode(65+(number%26));
}
checkCode+=code;
}
return checkCode;
}
]]>
</mx:Script>
<mx:Panel width="318" height="210" layout="absolute" title="Flex登陆界面" id="panel"
horizontalAlign="center" verticalAlign="middle" color="#1894AF"
fontFamily="Georgia" horizontalCenter="-16" verticalCenter="-17" fontSize="12" themeColor="#0356FE" fontWeight="normal">
<mx:Label x="36" y="29" text="用户名:" fontSize="12"/>
<mx:Label x="36" y="60" text="密 码:" width="45" fontSize="12"/>
<mx:TextInput x="93" y="27" id="txtUsername"/>
<mx:TextInput x="93" y="58" id="txtPassword" displayAsPassword="true" editable="true"/>
<mx:Button x="95" y="130" label="登陆" id="btnLogin" click="loginHandle();" fontSize="12" fontWeight="bold"/>
<mx:Button x="177" y="130" label="重置" id="btnReset" click="resetHandle();" fontSize="12"/>
<mx:Text x="34" y="91" text="验证码:" width="54" fontSize="12"/>
<mx:TextInput x="94" y="89" width="49" id="txtCheckCode" fontSize="12"/>
<mx:Text x="152" y="91" width="47" id="lblCheckCode" fontSize="14"/>
<mx:LinkButton x="199" y="89" label="看不清?" width="71" id="LinkbtnReGreateCode" click="lblCheckCode.text=GrearateCheckCode()" fontSize="12" fontWeight="normal"/>
</mx:Panel>
</mx:Application>