使用正则表达式进行数据有效性校验的TextBox控件
2024-07-21 02:23:50
供稿:网友
//导入程序使用的.net类库
using system;
using system.drawing;
using system.windows.forms;
using system.text.regularexpressions;
//命名空间regexeditor,以后将继续扩充....
namespace regexeditor
{
/** regextextbox继承自textbox控件
* 能够通过正则表达式对数据进行有效性校验
*/
public class regextextbox : system.windows.forms.textbox
{
private string strregex;//用于校验的正则表达式
private string strverifyerror;//校验错误的提示
private bool bisverifysuccess;//是否检验成功
private bool bisdisplayerror;//是否显示错误
private bool btoverify;//是否进行校验
//属性:用于校验的正则表达式
public string regexstring
{
get
{
return strregex;
}
set
{
strregex = value;
}
}
//属性:检验错误的提示
public string verifyerrorstring
{
get
{
return strverifyerror;
}
set
{
strverifyerror = value;
}
}
//属性:是否检验成功
public bool isverifysuccess
{
get
{
return bisverifysuccess;
}
set
{
bisverifysuccess = value;
}
}
//属性:是否显示校验错误
public bool isdisplayerror
{
get
{
return bisdisplayerror;
}
set
{
bisdisplayerror = value;
}
}
public bool toverify
{
get
{
return btoverify;
}
set
{
btoverify = value;
}
}
//构造函数
public regextextbox()
{
initializecomponent();
}
//初始化变量以及控件属性
void initializecomponent()
{
regexstring = "";
verifyerrorstring = "";
isverifysuccess = true;
isdisplayerror = false;
toverify = false;
this.name = "regextextbox";
this.validating += new system.componentmodel.canceleventhandler(this.onvalidatingdata);
}
//私有过程:校验数据
private bool verifydata()
{
isverifysuccess = regex.ismatch(this.text,regexstring);
return isverifysuccess;
}
//事件处理函数:校验数据
private void onvalidatingdata(object sender, system.componentmodel.canceleventargs e)
{
if(!toverify)//不需要校验直接退出
{
e.cancel = false;
return;
}
if(!verifydata())//校验不正确..
{
if(this.isdisplayerror)//要求显示校验错误提示..
{
messagebox.show(verifyerrorstring,"警告:");
}
else//要求不显示校验错误提示..
{
this.selectall();
}//end if
e.cancel = true;
}
else//校验正确..
{
e.cancel = false;
}//end if
}
}//end class
}//end namespace