如何验证Editor中输入的数据合法性
当user在ultraTextEditor中输入文本后, 有时我们需要check该数据是否是合法的, 比如一个Item No., 它的合法格式是xx.xxxxx.xxx, 其中x代表数字或字母, 如果user输入不是这种形式的数据将是不允许的, 因此有必要对数据的合法性进行check. 这里我们使用Validate事件作check.
(1) 为什么用Validate事件而不用传统的LostFocus(.Net中是Leave)
下面的代码是ultraMaskedEdit1的三个事件, 分别是Leave,Validated和Validating,当点击ToolBar上的Exit按钮时看哪些能够触发.
private void ultraTextEditor1_Leave(object sender, EventArgs e)
{
MessageBox.Show("Leave event Occured!");
}
private void ultraTextEditor1_Validated(object sender, EventArgs e)
{
MessageBox.Show("Validated event Occured!");
}
private void ultraTextEditor1_Validating(object sender, CancelEventArgs e)
{
MessageBox.Show("Validating event Occured!");
}
|
![](http://p.blog.csdn.net/images/p_blog_csdn_net/venus0314/606305eb1efd46589e7dd3f0ab58d8ca.png)
![](http://p.blog.csdn.net/images/p_blog_csdn_net/venus0314/222de7c8179444249e0d2b6ad1d5bc4c.png)
![](http://p.blog.csdn.net/images/p_blog_csdn_net/venus0314/200386a0bc0d4613bb883caaff23fba7.png)
结果是Validating和Validated是触发的, 而Leave没有, 这说明当在ultraTextEditor输入数据后希望在点ToolBar上的按钮前通过Leave事件作check是行不通的, 而用Validating和Validated是可以的.
(2) 如何进行Check
在Validating和Validated事件中check. 下面以check 一个Item No. 为例, 在Validating写check 逻辑:
private void ultraTextEditor1_Validating(object sender, CancelEventArgs e)
{
string strPattern = "^[A-Z0-9]{2}[.]{1}[A-Z0-9]{5}[.]{1}[A-Z0-9]{3}$";
Regex objReg = new Regex(strPattern);
if (objReg.IsMatch(ultraTextEditor1.Text) == false)
{
e.Cancel = true;
MessageBox.Show("Incorrect Item No. format!");
ultraTextEditor1.Text = "";
}
}
|
1333.3333.3333不是一个合法的Item No.,在Validating中验证失败, e.Cancel就赋true,
![](http://p.blog.csdn.net/images/p_blog_csdn_net/venus0314/830ec53107f0410199fd1a90dece2530.gif)
![](http://p.blog.csdn.net/images/p_blog_csdn_net/venus0314/a010ac8f21084fbfb5d6e798132f879a.png)
后面的Validated事件就不会触发.
如果验证通过, 后面的Validated会触发, 还可以在其中写其他的逻辑. 如下所示, 当验证通过后就选中文本:
private void ultraTextEditor1_Validated(object sender, EventArgs e)
{
ultraTextEditor1.Select();
}
|
如下所示, “AB.12345.EFG”是一个合法的ItemNo. , 验证通过后就选中文本.
![](http://p.blog.csdn.net/images/p_blog_csdn_net/venus0314/ca9e872b1a2744ffa8950124a18401e8.gif)
![](http://p.blog.csdn.net/images/p_blog_csdn_net/venus0314/818dce8957124bbda9410be37bb0aff7.gif)