(七十六)c#Winform自定义控件-表单验证组件

官网

http://www.hzhcontrols.com

前提

入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章。

GitHub:https://github.com/kwwwvagaa/NetWinformControl

码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git

如果觉得写的还行,请点个 star 支持一下吧

欢迎前来交流探讨: 企鹅群568015492 企鹅群568015492

来都来了,点个【推荐】再走吧,谢谢

NuGet

Install-Package HZH_Controls

目录

https://www.cnblogs.com/bfyx/p/11364884.html

用处及效果

准备工作

思路如下:

1、确定哪些控件需要进行验证,在组件中进行属性扩展

2、定义验证规则

3、根据验证规则的正则表达式进行验证和非空验证

4、触发验证结果事件

5、进行验证结果提示

开始

添加一个验证规则枚举

 1  /// <summary>
 2     /// 验证规则
 3     /// </summary>
 4     public enum VerificationModel
 5     {
 6         /// <summary>
 7         /// 8         /// </summary>
 9         [Description(""), VerificationAttribute()]
10         None = 1,
11         /// <summary>
12         /// 任意字母数字下划线
13         /// </summary>
14         [Description("任意字母数字下划线"), VerificationAttribute(@"^[a-zA-Z_0-1]*$", "请输入任意字母数字下划线")]
15         AnyChar = 2,
16         /// <summary>
17         /// 任意数字
18         /// </summary>
19         [Description("任意数字"), VerificationAttribute(@"^[\-\+]?\d+(\.\d+)?$", "请输入任意数字")]
20         Number = 4,
21         /// <summary>
22         /// 非负数
23         /// </summary>
24         [Description("非负数"), VerificationAttribute(@"^(\+)?\d+(\.\d+)?$", "请输入非负数")]
25         UnsignNumber = 8,
26         /// <summary>
27         /// 正数
28         /// </summary>
29         [Description("正数"), VerificationAttribute(@"(\+)?([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})", "请输入正数")]
30         PositiveNumber = 16,
31         /// <summary>
32         /// 整数
33         /// </summary>
34         [Description("整数"), VerificationAttribute(@"^[\+\-]?\d+$", "请输入整数")]
35         Integer = 32,
36         /// <summary>
37         /// 非负整数
38         /// </summary>
39         [Description("非负整数"), VerificationAttribute(@"^(\+)?\d+$", "请输入非负整数")]
40         UnsignIntegerNumber = 64,
41         /// <summary>
42         /// 正整数
43         /// </summary>
44         [Description("正整数"), VerificationAttribute(@"^[0-9]*[1-9][0-9]*$", "请输入正整数")]
45         PositiveIntegerNumber = 128,
46         /// <summary>
47         /// 邮箱
48         /// </summary>
49         [Description("邮箱"), VerificationAttribute(@"^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2}|net|NET|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT)$", "请输入正确的邮箱地址")]
50         Email = 256,
51         /// <summary>
52         /// 手机
53         /// </summary>
54         [Description("手机"), VerificationAttribute(@"^(\+?86)?1\d{10}$", "请输入正确的手机号")]
55         Phone = 512,
56         /// <summary>
57         /// IP
58         /// </summary>
59         [Description("IP"), VerificationAttribute(@"(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))", "请输入正确的IP地址")]
60         IP = 1024,
61         /// <summary>
62         /// Url
63         /// </summary>
64         [Description("Url"), VerificationAttribute(@"^[a-zA-z]+://(//w+(-//w+)*)(//.(//w+(-//w+)*))*(//?//S*)?$", "请输入正确的网址")]
65         URL = 2048,
66         /// <summary>
67         /// 身份证号
68         /// </summary>
69         [Description("身份证号"), VerificationAttribute(@"^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$", "请输入正确的身份证号")]
70         IDCardNo = 4096,
71         /// <summary>
72         /// 正则验证
73         /// </summary>
74         [Description("自定义正则表达式"), VerificationAttribute()]
75         Custom = 8192,
76     }

还有一个验证规则枚举的特性

 1  public class VerificationAttribute : Attribute
 2     {
 3         /// <summary>
 4         /// Initializes a new instance of the <see cref="VerificationAttribute"/> class.
 5         /// </summary>
 6         /// <param name="strRegex">The string regex.</param>
 7         /// <param name="strErrorMsg">The string error MSG.</param>
 8         public VerificationAttribute(string strRegex = "", string strErrorMsg = "")
 9         {
10             Regex = strRegex;
11             ErrorMsg = strErrorMsg;
12         }
13         /// <summary>
14         /// Gets or sets the regex.
15         /// </summary>
16         /// <value>The regex.</value>
17         public string Regex { get; set; }
18         /// <summary>
19         /// Gets or sets the error MSG.
20         /// </summary>
21         /// <value>The error MSG.</value>
22         public string ErrorMsg { get; set; }
23 
24     }

定义事件参数

 1  public class VerificationEventArgs : EventArgs
 2     {
 3         /// <summary>
 4         /// Gets or sets the verification control.
 5         /// </summary>
 6         /// <value>The verification control.</value>
 7         public Control VerificationControl { get; set; }
 8         /// <summary>
 9         /// Gets or sets a value indicating whether [verify success].
10         /// </summary>
11         /// <value><c>true</c> if [verify success]; otherwise, <c>false</c>.</value>
12         public bool IsVerifySuccess { get; set; }
13         /// <summary>
14         /// Gets or sets the verification model.
15         /// </summary>
16         /// <value>The verification model.</value>
17         public VerificationModel VerificationModel { get; set; }
18         /// <summary>
19         /// 是否已处理,如果为true,则不再使用默认验证提示功能
20         /// </summary>
21         /// <value><c>true</c> if this instance is processed; otherwise, <c>false</c>.</value>
22         public bool IsProcessed { get; set; }
23         /// <summary>
24         /// Gets or sets 正则表达式
25         /// </summary>
26         /// <value>The custom regex.</value>
27         public string Regex { get; set; }
28         /// <summary>
29         /// Gets or sets a value indicating whether this <see cref="VerificationEventArgs"/> is required.
30         /// </summary>
31         /// <value><c>true</c> if required; otherwise, <c>false</c>.</value>
32         public bool Required { get; set; }
33 
34         /// <summary>
35         /// Gets or sets the error MSG.
36         /// </summary>
37         /// <value>The error MSG.</value>
38         public string ErrorMsg { get; set; }
39     }

添加一个类VerificationComponent继承Component,实现接口 IExtenderProvider以对控件进行扩展

定义属性

 1   /// <summary>
 2         /// Delegate VerificationedHandle
 3         /// </summary>
 4         /// <param name="e">The <see cref="VerificationEventArgs"/> instance containing the event data.</param>
 5         public delegate void VerificationedHandle(VerificationEventArgs e);
 6         /// <summary>
 7         /// Occurs when [verificationed].
 8         /// </summary>
 9         [Browsable(true), Category("自定义属性"), Description("验证事件"), Localizable(true)]
10         public event VerificationedHandle Verificationed;
11 
12         /// <summary>
13         /// The m control cache
14         /// </summary>
15         Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>();
16         /// <summary>
17         /// The m control regex cache
18         /// </summary>
19         Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>();
20         /// <summary>
21         /// The m control required cache
22         /// </summary>
23         Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>();
24         /// <summary>
25         /// The m control MSG cache
26         /// </summary>
27         Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>();
28         /// <summary>
29         /// The m control tips
30         /// </summary>
31         Dictionary<Control, Forms.FrmAnchorTips> m_controlTips = new Dictionary<Control, Forms.FrmAnchorTips>();
32 
33         /// <summary>
34         /// The error tips back color
35         /// </summary>
36         private Color errorTipsBackColor = Color.FromArgb(255, 77, 58);
37 
38         /// <summary>
39         /// Gets or sets the color of the error tips back.
40         /// </summary>
41         /// <value>The color of the error tips back.</value>
42         [Browsable(true), Category("自定义属性"), Description("错误提示背景色"), Localizable(true)]
43         public Color ErrorTipsBackColor
44         {
45             get { return errorTipsBackColor; }
46             set { errorTipsBackColor = value; }
47         }
48 
49         /// <summary>
50         /// The error tips fore color
51         /// </summary>
52         private Color errorTipsForeColor = Color.White;
53 
54         /// <summary>
55         /// Gets or sets the color of the error tips fore.
56         /// </summary>
57         /// <value>The color of the error tips fore.</value>
58         [Browsable(true), Category("自定义属性"), Description("错误提示文字颜色"), Localizable(true)]
59         public Color ErrorTipsForeColor
60         {
61             get { return errorTipsForeColor; }
62             set { errorTipsForeColor = value; }
63         }

 

哪些控件需要进行验证(属性扩展)

1  public bool CanExtend(object extendee)
2         {
3             if (extendee is TextBoxBase || extendee is UCTextBoxEx || extendee is ComboBox || extendee is UCCombox)
4             {
5                 return true;
6             }
7             return false;
8         }

扩展属性

  1   /// <summary>
  2         /// The m control cache
  3         /// </summary>
  4         Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>();
  5         /// <summary>
  6         /// The m control regex cache
  7         /// </summary>
  8         Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>();
  9         /// <summary>
 10         /// The m control required cache
 11         /// </summary>
 12         Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>();
 13         /// <summary>
 14         /// The m control MSG cache
 15         /// </summary>
 16         Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>();
 17 
 18   #region 验证规则    English:Validation rule
 19         /// <summary>
 20         /// Gets the verification model.
 21         /// </summary>
 22         /// <param name="control">The control.</param>
 23         /// <returns>VerificationModel.</returns>
 24         [Browsable(true), Category("自定义属性"), Description("验证规则"), DisplayName("VerificationModel"), Localizable(true)]
 25         public VerificationModel GetVerificationModel(Control control)
 26         {
 27             if (m_controlCache.ContainsKey(control))
 28             {
 29                 return m_controlCache[control];
 30             }
 31             else
 32                 return VerificationModel.None;
 33         }
 34 
 35         /// <summary>
 36         /// Sets the verification model.
 37         /// </summary>
 38         /// <param name="control">The control.</param>
 39         /// <param name="vm">The vm.</param>
 40         public void SetVerificationModel(Control control, VerificationModel vm)
 41         {
 42             m_controlCache[control] = vm;
 43         }
 44         #endregion
 45 
 46         #region 自定义正则    English:Custom Rules
 47         /// <summary>
 48         /// Gets the verification custom regex.
 49         /// </summary>
 50         /// <param name="control">The control.</param>
 51         /// <returns>System.String.</returns>
 52         [Browsable(true), Category("自定义属性"), Description("自定义验证正则表达式"), DisplayName("VerificationCustomRegex"), Localizable(true)]
 53         public string GetVerificationCustomRegex(Control control)
 54         {
 55             if (m_controlRegexCache.ContainsKey(control))
 56             {
 57                 return m_controlRegexCache[control];
 58             }
 59             else
 60                 return "";
 61         }
 62 
 63         /// <summary>
 64         /// Sets the verification custom regex.
 65         /// </summary>
 66         /// <param name="control">The control.</param>
 67         /// <param name="strRegex">The string regex.</param>
 68         public void SetVerificationCustomRegex(Control control, string strRegex)
 69         {
 70             m_controlRegexCache[control] = strRegex;
 71         }
 72         #endregion
 73 
 74         #region 必填    English:Must fill
 75         /// <summary>
 76         /// Gets the verification required.
 77         /// </summary>
 78         /// <param name="control">The control.</param>
 79         /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
 80         [Browsable(true), Category("自定义属性"), Description("是否必填项"), DisplayName("VerificationRequired"), Localizable(true)]
 81         public bool GetVerificationRequired(Control control)
 82         {
 83             if (m_controlRequiredCache.ContainsKey(control))
 84                 return m_controlRequiredCache[control];
 85             return false;
 86         }
 87 
 88         /// <summary>
 89         /// Sets the verification required.
 90         /// </summary>
 91         /// <param name="control">The control.</param>
 92         /// <param name="blnRequired">if set to <c>true</c> [BLN required].</param>
 93         public void SetVerificationRequired(Control control, bool blnRequired)
 94         {
 95             m_controlRequiredCache[control] = blnRequired;
 96         }
 97         #endregion
 98 
 99         #region 提示信息    English:Prompt information
100         /// <summary>
101         /// Gets the verification error MSG.
102         /// </summary>
103         /// <param name="control">The control.</param>
104         /// <returns>System.String.</returns>
105         [Browsable(true), Category("自定义属性"), Description("验证错误提示信息,当为空时则使用默认提示信息"), DisplayName("VerificationErrorMsg"), Localizable(true)]
106         public string GetVerificationErrorMsg(Control control)
107         {
108             if (m_controlMsgCache.ContainsKey(control))
109                 return m_controlMsgCache[control];
110             return "";
111         }
112 
113         /// <summary>
114         /// Sets the verification error MSG.
115         /// </summary>
116         /// <param name="control">The control.</param>
117         /// <param name="strErrorMsg">The string error MSG.</param>
118         public void SetVerificationErrorMsg(Control control, string strErrorMsg)
119         {
120             m_controlMsgCache[control] = strErrorMsg;
121         }
122         #endregion

验证处理

  1   #region 验证    English:Verification
  2         /// <summary>
  3         /// 功能描述:验证    English:Verification result processing
  4         /// 作  者:HZH
  5         /// 创建日期:2019-09-28 09:02:49
  6         /// 任务编号:POS
  7         /// </summary>
  8         /// <param name="c">c</param>
  9         /// <returns>返回值</returns>
 10         public bool Verification(Control c)
 11         {
 12             bool bln = true;
 13             if (m_controlCache.ContainsKey(c))
 14             {
 15                 var vm = m_controlCache[c];
 16                 string strRegex = "";
 17                 string strErrMsg = "";
 18                 #region 获取正则或默认错误提示    English:Get regular or error prompts
 19                 if (vm == VerificationModel.Custom)
 20                 {
 21                     //自定义正则
 22                     if (m_controlRegexCache.ContainsKey(c))
 23                     {
 24                         strRegex = m_controlRegexCache[c];
 25                         strErrMsg = "不正确的输入";
 26                     }
 27                 }
 28                 else
 29                 {
 30                     //获取默认正则和错误提示
 31                     Type type = vm.GetType();   //获取类型  
 32                     MemberInfo[] memberInfos = type.GetMember(vm.ToString());
 33                     if (memberInfos.Length > 0)
 34                     {
 35                         var atts = memberInfos[0].GetCustomAttributes(typeof(VerificationAttribute), false);
 36                         if (atts.Length > 0)
 37                         {
 38                             var va = ((VerificationAttribute)atts[0]);
 39                             strErrMsg = va.ErrorMsg;
 40                             strRegex = va.Regex;
 41                         }
 42                     }
 43                 }
 44                 #endregion
 45 
 46                 #region 取值    English:Value
 47                 string strValue = "";
 48                 if (c is TextBoxBase)
 49                 {
 50                     strValue = (c as TextBoxBase).Text;
 51                 }
 52                 else if (c is UCTextBoxEx)
 53                 {
 54                     strValue = (c as UCTextBoxEx).InputText;
 55                 }
 56                 else if (c is ComboBox)
 57                 {
 58                     var cbo = (c as ComboBox);
 59                     if (cbo.DropDownStyle == ComboBoxStyle.DropDownList)
 60                     {
 61                         strValue = cbo.SelectedItem == null ? "" : cbo.SelectedValue.ToString();
 62                     }
 63                     else
 64                     {
 65                         strValue = cbo.Text;
 66                     }
 67                 }
 68                 else if (c is UCCombox)
 69                 {
 70                     strValue = (c as UCCombox).SelectedText;
 71                 }
 72                 #endregion
 73 
 74                 //自定义错误信息
 75                 if (m_controlMsgCache.ContainsKey(c) && !string.IsNullOrEmpty(m_controlMsgCache[c]))
 76                     strErrMsg = m_controlMsgCache[c];
 77 
 78                 //检查必填项
 79                 if (m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c])
 80                 {
 81                     if (string.IsNullOrEmpty(strValue))
 82                     {
 83                         VerControl(new VerificationEventArgs()
 84                         {
 85                             VerificationModel = vm,
 86                             Regex = strRegex,
 87                             ErrorMsg = "不能为空",
 88                             IsVerifySuccess = false,
 89                             Required = true,
 90                             VerificationControl = c
 91                         });
 92                         bln = false;
 93                         return false;
 94                     }
 95                 }
 96                 //验证正则
 97                 if (!string.IsNullOrEmpty(strValue))
 98                 {
 99                     if (!string.IsNullOrEmpty(strRegex))
100                     {
101                         if (!Regex.IsMatch(strValue, strRegex))
102                         {
103                             VerControl(new VerificationEventArgs()
104                             {
105                                 VerificationModel = vm,
106                                 Regex = strRegex,
107                                 ErrorMsg = strErrMsg,
108                                 IsVerifySuccess = false,
109                                 Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],
110                                 VerificationControl = c
111                             });
112                             bln = false;
113                             return false;
114                         }
115                     }
116                 }
117                 //没有问题出发一个成功信息
118                 VerControl(new VerificationEventArgs()
119                 {
120                     VerificationModel = vm,
121                     Regex = strRegex,
122                     ErrorMsg = strErrMsg,
123                     IsVerifySuccess = true,
124                     Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],
125                     VerificationControl = c
126                 });
127             }
128             return bln;
129         }
130         #endregion
131         #region 验证    English:Verification
132         /// <summary>
133         /// 功能描述:验证    English:Verification
134         /// 作  者:HZH
135         /// 创建日期:2019-09-27 17:54:38
136         /// 任务编号:POS
137         /// </summary>
138         /// <returns>返回值</returns>
139         public bool Verification()
140         {
141             bool bln = true;
142             foreach (var item in m_controlCache)
143             {
144                 Control c = item.Key;
145                 if (!Verification(c))
146                 {
147                     bln = false;
148                 }
149             }
150             return bln;
151         }
152         #endregion
153 
154 
155 
156         #region 验证结果处理    English:Verification result processing
157         /// <summary>
158         /// 功能描述:验证结果处理    English:Verification result processing
159         /// 作  者:HZH
160         /// 创建日期:2019-09-27 17:54:59
161         /// 任务编号:POS
162         /// </summary>
163         /// <param name="e">e</param>
164         private void VerControl(VerificationEventArgs e)
165         {
166             //如果成功则移除失败提示
167             if (e.IsVerifySuccess)
168             {
169                 if (m_controlTips.ContainsKey(e.VerificationControl))
170                 {
171                     m_controlTips[e.VerificationControl].Close();
172                     m_controlTips.Remove(e.VerificationControl);
173                 }
174             }
175             //触发事件
176             if (Verificationed != null)
177             {
178                 Verificationed(e);
179                 if (e.IsProcessed)//如果已处理,则不再向下执行
180                 {
181                     return;
182                 }
183             }
184             //如果失败则显示提示
185             if (!e.IsVerifySuccess)
186             {
187                 if (m_controlTips.ContainsKey(e.VerificationControl))
188                 {
189                     m_controlTips[e.VerificationControl].StrMsg = e.ErrorMsg;
190                 }
191                 else
192                 {
193                     var tips = Forms.FrmAnchorTips.ShowTips(e.VerificationControl, e.ErrorMsg, background: errorTipsBackColor, foreColor: errorTipsForeColor, autoCloseTime: 0, blnTopMost: false);
194                     m_controlTips[e.VerificationControl] = tips;
195                 }
196             }
197         }
198         #endregion

完整代码

  1 // ***********************************************************************
  2 // Assembly         : HZH_Controls
  3 // Created          : 2019-09-27
  4 //
  5 // ***********************************************************************
  6 // <copyright file="VerificationComponent.cs">
  7 //     Copyright by Huang Zhenghui(黄正辉) All, QQ group:568015492 QQ:623128629 Email:623128629@qq.com
  8 // </copyright>
  9 //
 10 // Blog: https://www.cnblogs.com/bfyx
 11 // GitHub:https://github.com/kwwwvagaa/NetWinformControl
 12 // gitee:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
 13 //
 14 // If you use this code, please keep this note.
 15 // ***********************************************************************
 16 using System;
 17 using System.Collections.Generic;
 18 using System.ComponentModel;
 19 using System.Drawing;
 20 using System.Linq;
 21 using System.Reflection;
 22 using System.Text;
 23 using System.Text.RegularExpressions;
 24 using System.Windows.Forms;
 25 
 26 namespace HZH_Controls.Controls
 27 {
 28     /// <summary>
 29     /// Class VerificationComponent.
 30     /// Implements the <see cref="System.ComponentModel.Component" />
 31     /// Implements the <see cref="System.ComponentModel.IExtenderProvider" />
 32     /// </summary>
 33     /// <seealso cref="System.ComponentModel.Component" />
 34     /// <seealso cref="System.ComponentModel.IExtenderProvider" />
 35     [ProvideProperty("VerificationModel", typeof(Control))]
 36     [ProvideProperty("VerificationCustomRegex", typeof(Control))]
 37     [ProvideProperty("VerificationRequired", typeof(Control))]
 38     [ProvideProperty("VerificationErrorMsg", typeof(Control))]
 39     [DefaultEvent("Verificationed")]
 40     public class VerificationComponent : Component, IExtenderProvider
 41     {
 42         /// <summary>
 43         /// Delegate VerificationedHandle
 44         /// </summary>
 45         /// <param name="e">The <see cref="VerificationEventArgs"/> instance containing the event data.</param>
 46         public delegate void VerificationedHandle(VerificationEventArgs e);
 47         /// <summary>
 48         /// Occurs when [verificationed].
 49         /// </summary>
 50         [Browsable(true), Category("自定义属性"), Description("验证事件"), Localizable(true)]
 51         public event VerificationedHandle Verificationed;
 52 
 53         /// <summary>
 54         /// The m control cache
 55         /// </summary>
 56         Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>();
 57         /// <summary>
 58         /// The m control regex cache
 59         /// </summary>
 60         Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>();
 61         /// <summary>
 62         /// The m control required cache
 63         /// </summary>
 64         Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>();
 65         /// <summary>
 66         /// The m control MSG cache
 67         /// </summary>
 68         Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>();
 69         /// <summary>
 70         /// The m control tips
 71         /// </summary>
 72         Dictionary<Control, Forms.FrmAnchorTips> m_controlTips = new Dictionary<Control, Forms.FrmAnchorTips>();
 73 
 74         /// <summary>
 75         /// The error tips back color
 76         /// </summary>
 77         private Color errorTipsBackColor = Color.FromArgb(255, 77, 58);
 78 
 79         /// <summary>
 80         /// Gets or sets the color of the error tips back.
 81         /// </summary>
 82         /// <value>The color of the error tips back.</value>
 83         [Browsable(true), Category("自定义属性"), Description("错误提示背景色"), Localizable(true)]
 84         public Color ErrorTipsBackColor
 85         {
 86             get { return errorTipsBackColor; }
 87             set { errorTipsBackColor = value; }
 88         }
 89 
 90         /// <summary>
 91         /// The error tips fore color
 92         /// </summary>
 93         private Color errorTipsForeColor = Color.White;
 94 
 95         /// <summary>
 96         /// Gets or sets the color of the error tips fore.
 97         /// </summary>
 98         /// <value>The color of the error tips fore.</value>
 99         [Browsable(true), Category("自定义属性"), Description("错误提示文字颜色"), Localizable(true)]
100         public Color ErrorTipsForeColor
101         {
102             get { return errorTipsForeColor; }
103             set { errorTipsForeColor = value; }
104         }
105 
106         #region 构造函数    English:Constructor
107         /// <summary>
108         /// Initializes a new instance of the <see cref="VerificationComponent"/> class.
109         /// </summary>
110         public VerificationComponent()
111         {
112 
113         }
114 
115         /// <summary>
116         /// Initializes a new instance of the <see cref="VerificationComponent"/> class.
117         /// </summary>
118         /// <param name="container">The container.</param>
119         public VerificationComponent(IContainer container)
120             : this()
121         {
122             container.Add(this);
123         }
124         #endregion
125 
126         #region 指定此对象是否可以将其扩展程序属性提供给指定的对象。    English:Specifies whether this object can provide its extender properties to the specified object.
127         /// <summary>
128         /// 指定此对象是否可以将其扩展程序属性提供给指定的对象。
129         /// </summary>
130         /// <param name="extendee">要接收扩展程序属性的 <see cref="T:System.Object" /></param>
131         /// <returns>如果此对象可以扩展程序属性提供给指定对象,则为 true;否则为 false。</returns>
132         public bool CanExtend(object extendee)
133         {
134             if (extendee is TextBoxBase || extendee is UCTextBoxEx || extendee is ComboBox || extendee is UCCombox)
135             {
136                 return true;
137             }
138             return false;
139         }
140         #endregion
141 
142         #region 验证规则    English:Validation rule
143         /// <summary>
144         /// Gets the verification model.
145         /// </summary>
146         /// <param name="control">The control.</param>
147         /// <returns>VerificationModel.</returns>
148         [Browsable(true), Category("自定义属性"), Description("验证规则"), DisplayName("VerificationModel"), Localizable(true)]
149         public VerificationModel GetVerificationModel(Control control)
150         {
151             if (m_controlCache.ContainsKey(control))
152             {
153                 return m_controlCache[control];
154             }
155             else
156                 return VerificationModel.None;
157         }
158 
159         /// <summary>
160         /// Sets the verification model.
161         /// </summary>
162         /// <param name="control">The control.</param>
163         /// <param name="vm">The vm.</param>
164         public void SetVerificationModel(Control control, VerificationModel vm)
165         {
166             m_controlCache[control] = vm;
167         }
168         #endregion
169 
170         #region 自定义正则    English:Custom Rules
171         /// <summary>
172         /// Gets the verification custom regex.
173         /// </summary>
174         /// <param name="control">The control.</param>
175         /// <returns>System.String.</returns>
176         [Browsable(true), Category("自定义属性"), Description("自定义验证正则表达式"), DisplayName("VerificationCustomRegex"), Localizable(true)]
177         public string GetVerificationCustomRegex(Control control)
178         {
179             if (m_controlRegexCache.ContainsKey(control))
180             {
181                 return m_controlRegexCache[control];
182             }
183             else
184                 return "";
185         }
186 
187         /// <summary>
188         /// Sets the verification custom regex.
189         /// </summary>
190         /// <param name="control">The control.</param>
191         /// <param name="strRegex">The string regex.</param>
192         public void SetVerificationCustomRegex(Control control, string strRegex)
193         {
194             m_controlRegexCache[control] = strRegex;
195         }
196         #endregion
197 
198         #region 必填    English:Must fill
199         /// <summary>
200         /// Gets the verification required.
201         /// </summary>
202         /// <param name="control">The control.</param>
203         /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
204         [Browsable(true), Category("自定义属性"), Description("是否必填项"), DisplayName("VerificationRequired"), Localizable(true)]
205         public bool GetVerificationRequired(Control control)
206         {
207             if (m_controlRequiredCache.ContainsKey(control))
208                 return m_controlRequiredCache[control];
209             return false;
210         }
211 
212         /// <summary>
213         /// Sets the verification required.
214         /// </summary>
215         /// <param name="control">The control.</param>
216         /// <param name="blnRequired">if set to <c>true</c> [BLN required].</param>
217         public void SetVerificationRequired(Control control, bool blnRequired)
218         {
219             m_controlRequiredCache[control] = blnRequired;
220         }
221         #endregion
222 
223         #region 提示信息    English:Prompt information
224         /// <summary>
225         /// Gets the verification error MSG.
226         /// </summary>
227         /// <param name="control">The control.</param>
228         /// <returns>System.String.</returns>
229         [Browsable(true), Category("自定义属性"), Description("验证错误提示信息,当为空时则使用默认提示信息"), DisplayName("VerificationErrorMsg"), Localizable(true)]
230         public string GetVerificationErrorMsg(Control control)
231         {
232             if (m_controlMsgCache.ContainsKey(control))
233                 return m_controlMsgCache[control];
234             return "";
235         }
236 
237         /// <summary>
238         /// Sets the verification error MSG.
239         /// </summary>
240         /// <param name="control">The control.</param>
241         /// <param name="strErrorMsg">The string error MSG.</param>
242         public void SetVerificationErrorMsg(Control control, string strErrorMsg)
243         {
244             m_controlMsgCache[control] = strErrorMsg;
245         }
246         #endregion
247 
248 
249         #region 验证    English:Verification
250         /// <summary>
251         /// 功能描述:验证    English:Verification result processing
252         /// 作  者:HZH
253         /// 创建日期:2019-09-28 09:02:49
254         /// 任务编号:POS
255         /// </summary>
256         /// <param name="c">c</param>
257         /// <returns>返回值</returns>
258         public bool Verification(Control c)
259         {
260             bool bln = true;
261             if (m_controlCache.ContainsKey(c))
262             {
263                 var vm = m_controlCache[c];
264                 string strRegex = "";
265                 string strErrMsg = "";
266                 #region 获取正则或默认错误提示    English:Get regular or error prompts
267                 if (vm == VerificationModel.Custom)
268                 {
269                     //自定义正则
270                     if (m_controlRegexCache.ContainsKey(c))
271                     {
272                         strRegex = m_controlRegexCache[c];
273                         strErrMsg = "不正确的输入";
274                     }
275                 }
276                 else
277                 {
278                     //获取默认正则和错误提示
279                     Type type = vm.GetType();   //获取类型  
280                     MemberInfo[] memberInfos = type.GetMember(vm.ToString());
281                     if (memberInfos.Length > 0)
282                     {
283                         var atts = memberInfos[0].GetCustomAttributes(typeof(VerificationAttribute), false);
284                         if (atts.Length > 0)
285                         {
286                             var va = ((VerificationAttribute)atts[0]);
287                             strErrMsg = va.ErrorMsg;
288                             strRegex = va.Regex;
289                         }
290                     }
291                 }
292                 #endregion
293 
294                 #region 取值    English:Value
295                 string strValue = "";
296                 if (c is TextBoxBase)
297                 {
298                     strValue = (c as TextBoxBase).Text;
299                 }
300                 else if (c is UCTextBoxEx)
301                 {
302                     strValue = (c as UCTextBoxEx).InputText;
303                 }
304                 else if (c is ComboBox)
305                 {
306                     var cbo = (c as ComboBox);
307                     if (cbo.DropDownStyle == ComboBoxStyle.DropDownList)
308                     {
309                         strValue = cbo.SelectedItem == null ? "" : cbo.SelectedValue.ToString();
310                     }
311                     else
312                     {
313                         strValue = cbo.Text;
314                     }
315                 }
316                 else if (c is UCCombox)
317                 {
318                     strValue = (c as UCCombox).SelectedText;
319                 }
320                 #endregion
321 
322                 //自定义错误信息
323                 if (m_controlMsgCache.ContainsKey(c) && !string.IsNullOrEmpty(m_controlMsgCache[c]))
324                     strErrMsg = m_controlMsgCache[c];
325 
326                 //检查必填项
327                 if (m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c])
328                 {
329                     if (string.IsNullOrEmpty(strValue))
330                     {
331                         VerControl(new VerificationEventArgs()
332                         {
333                             VerificationModel = vm,
334                             Regex = strRegex,
335                             ErrorMsg = "不能为空",
336                             IsVerifySuccess = false,
337                             Required = true,
338                             VerificationControl = c
339                         });
340                         bln = false;
341                         return false;
342                     }
343                 }
344                 //验证正则
345                 if (!string.IsNullOrEmpty(strValue))
346                 {
347                     if (!string.IsNullOrEmpty(strRegex))
348                     {
349                         if (!Regex.IsMatch(strValue, strRegex))
350                         {
351                             VerControl(new VerificationEventArgs()
352                             {
353                                 VerificationModel = vm,
354                                 Regex = strRegex,
355                                 ErrorMsg = strErrMsg,
356                                 IsVerifySuccess = false,
357                                 Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],
358                                 VerificationControl = c
359                             });
360                             bln = false;
361                             return false;
362                         }
363                     }
364                 }
365                 //没有问题出发一个成功信息
366                 VerControl(new VerificationEventArgs()
367                 {
368                     VerificationModel = vm,
369                     Regex = strRegex,
370                     ErrorMsg = strErrMsg,
371                     IsVerifySuccess = true,
372                     Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],
373                     VerificationControl = c
374                 });
375             }
376             return bln;
377         }
378         #endregion
379         #region 验证    English:Verification
380         /// <summary>
381         /// 功能描述:验证    English:Verification
382         /// 作  者:HZH
383         /// 创建日期:2019-09-27 17:54:38
384         /// 任务编号:POS
385         /// </summary>
386         /// <returns>返回值</returns>
387         public bool Verification()
388         {
389             bool bln = true;
390             foreach (var item in m_controlCache)
391             {
392                 Control c = item.Key;
393                 if (!Verification(c))
394                 {
395                     bln = false;
396                 }
397             }
398             return bln;
399         }
400         #endregion
401 
402 
403 
404         #region 验证结果处理    English:Verification result processing
405         /// <summary>
406         /// 功能描述:验证结果处理    English:Verification result processing
407         /// 作  者:HZH
408         /// 创建日期:2019-09-27 17:54:59
409         /// 任务编号:POS
410         /// </summary>
411         /// <param name="e">e</param>
412         private void VerControl(VerificationEventArgs e)
413         {
414             //如果成功则移除失败提示
415             if (e.IsVerifySuccess)
416             {
417                 if (m_controlTips.ContainsKey(e.VerificationControl))
418                 {
419                     m_controlTips[e.VerificationControl].Close();
420                     m_controlTips.Remove(e.VerificationControl);
421                 }
422             }
423             //触发事件
424             if (Verificationed != null)
425             {
426                 Verificationed(e);
427                 if (e.IsProcessed)//如果已处理,则不再向下执行
428                 {
429                     return;
430                 }
431             }
432             //如果失败则显示提示
433             if (!e.IsVerifySuccess)
434             {
435                 if (m_controlTips.ContainsKey(e.VerificationControl))
436                 {
437                     m_controlTips[e.VerificationControl].StrMsg = e.ErrorMsg;
438                 }
439                 else
440                 {
441                     var tips = Forms.FrmAnchorTips.ShowTips(e.VerificationControl, e.ErrorMsg, background: errorTipsBackColor, foreColor: errorTipsForeColor, autoCloseTime: 0, blnTopMost: false);
442                     m_controlTips[e.VerificationControl] = tips;
443                 }
444             }
445         }
446         #endregion
447     }
448 }
View Code

 

最后的话

如果你喜欢的话,请到 https://gitee.com/kwwwvagaa/net_winform_custom_control 点个星星吧

posted @ 2019-09-28 09:42 冰封一夏 阅读(...) 评论(...) 编辑 收藏
HZHControls控件库官网:http://hzhcontrols.com