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


官网

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

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

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

定义事件参数

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

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

定义属性

 1   /// 
 2         /// Delegate VerificationedHandle
 3         /// 
 4         /// The  instance containing the event data.
 5         public delegate void VerificationedHandle(VerificationEventArgs e);
 6         /// 
 7         /// Occurs when [verificationed].
 8         /// 
 9         [Browsable(true), Category("自定义属性"), Description("验证事件"), Localizable(true)]
10         public event VerificationedHandle Verificationed;
11 
12         /// 
13         /// The m control cache
14         /// 
15         Dictionary m_controlCache = new Dictionary();
16         /// 
17         /// The m control regex cache
18         /// 
19         Dictionarystring> m_controlRegexCache = new Dictionarystring>();
20         /// 
21         /// The m control required cache
22         /// 
23         Dictionarybool> m_controlRequiredCache = new Dictionarybool>();
24         /// 
25         /// The m control MSG cache
26         /// 
27         Dictionarystring> m_controlMsgCache = new Dictionarystring>();
28         /// 
29         /// The m control tips
30         /// 
31         Dictionary m_controlTips = new Dictionary();
32 
33         /// 
34         /// The error tips back color
35         /// 
36         private Color errorTipsBackColor = Color.FromArgb(255, 77, 58);
37 
38         /// 
39         /// Gets or sets the color of the error tips back.
40         /// 
41         /// The color of the error tips back.
42         [Browsable(true), Category("自定义属性"), Description("错误提示背景色"), Localizable(true)]
43         public Color ErrorTipsBackColor
44         {
45             get { return errorTipsBackColor; }
46             set { errorTipsBackColor = value; }
47         }
48 
49         /// 
50         /// The error tips fore color
51         /// 
52         private Color errorTipsForeColor = Color.White;
53 
54         /// 
55         /// Gets or sets the color of the error tips fore.
56         /// 
57         /// The color of the error tips fore.
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   /// 
  2         /// The m control cache
  3         /// 
  4         Dictionary m_controlCache = new Dictionary();
  5         /// 
  6         /// The m control regex cache
  7         /// 
  8         Dictionarystring> m_controlRegexCache = new Dictionarystring>();
  9         /// 
 10         /// The m control required cache
 11         /// 
 12         Dictionarybool> m_controlRequiredCache = new Dictionarybool>();
 13         /// 
 14         /// The m control MSG cache
 15         /// 
 16         Dictionarystring> m_controlMsgCache = new Dictionarystring>();
 17 
 18   #region 验证规则    English:Validation rule
 19         /// 
 20         /// Gets the verification model.
 21         /// 
 22         /// The control.
 23         /// VerificationModel.
 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         /// 
 36         /// Sets the verification model.
 37         /// 
 38         /// The control.
 39         /// The vm.
 40         public void SetVerificationModel(Control control, VerificationModel vm)
 41         {
 42             m_controlCache[control] = vm;
 43         }
 44         #endregion
 45 
 46         #region 自定义正则    English:Custom Rules
 47         /// 
 48         /// Gets the verification custom regex.
 49         /// 
 50         /// The control.
 51         /// System.String.
 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         /// 
 64         /// Sets the verification custom regex.
 65         /// 
 66         /// The control.
 67         /// The string regex.
 68         public void SetVerificationCustomRegex(Control control, string strRegex)
 69         {
 70             m_controlRegexCache[control] = strRegex;
 71         }
 72         #endregion
 73 
 74         #region 必填    English:Must fill
 75         /// 
 76         /// Gets the verification required.
 77         /// 
 78         /// The control.
 79         /// true if XXXX, false otherwise.
 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         /// 
 89         /// Sets the verification required.
 90         /// 
 91         /// The control.
 92         /// if set to true [BLN required].
 93         public void SetVerificationRequired(Control control, bool blnRequired)
 94         {
 95             m_controlRequiredCache[control] = blnRequired;
 96         }
 97         #endregion
 98 
 99         #region 提示信息    English:Prompt information
100         /// 
101         /// Gets the verification error MSG.
102         /// 
103         /// The control.
104         /// System.String.
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         /// 
114         /// Sets the verification error MSG.
115         /// 
116         /// The control.
117         /// The string error MSG.
118         public void SetVerificationErrorMsg(Control control, string strErrorMsg)
119         {
120             m_controlMsgCache[control] = strErrorMsg;
121         }
122         #endregion

验证处理

  1   #region 验证    English:Verification
  2         /// 
  3         /// 功能描述:验证    English:Verification result processing
  4         /// 作  者:HZH
  5         /// 创建日期:2019-09-28 09:02:49
  6         /// 任务编号:POS
  7         /// 
  8         /// c
  9         /// 返回值
 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         /// 
133         /// 功能描述:验证    English:Verification
134         /// 作  者:HZH
135         /// 创建日期:2019-09-27 17:54:38
136         /// 任务编号:POS
137         /// 
138         /// 返回值
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         /// 
158         /// 功能描述:验证结果处理    English:Verification result processing
159         /// 作  者:HZH
160         /// 创建日期:2019-09-27 17:54:59
161         /// 任务编号:POS
162         /// 
163         /// e
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 // 
  7 //     Copyright by Huang Zhenghui(黄正辉) All, QQ group:568015492 QQ:623128629 Email:623128629@qq.com
  8 // 
  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     /// 
 29     /// Class VerificationComponent.
 30     /// Implements the 
 31     /// Implements the 
 32     /// 
 33     /// 
 34     /// 
 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         /// 
 43         /// Delegate VerificationedHandle
 44         /// 
 45         /// The  instance containing the event data.
 46         public delegate void VerificationedHandle(VerificationEventArgs e);
 47         /// 
 48         /// Occurs when [verificationed].
 49         /// 
 50         [Browsable(true), Category("自定义属性"), Description("验证事件"), Localizable(true)]
 51         public event VerificationedHandle Verificationed;
 52 
 53         /// 
 54         /// The m control cache
 55         /// 
 56         Dictionary m_controlCache = new Dictionary();
 57         /// 
 58         /// The m control regex cache
 59         /// 
 60         Dictionarystring> m_controlRegexCache = new Dictionarystring>();
 61         /// 
 62         /// The m control required cache
 63         /// 
 64         Dictionarybool> m_controlRequiredCache = new Dictionarybool>();
 65         /// 
 66         /// The m control MSG cache
 67         /// 
 68         Dictionarystring> m_controlMsgCache = new Dictionarystring>();
 69         /// 
 70         /// The m control tips
 71         /// 
 72         Dictionary m_controlTips = new Dictionary();
 73 
 74         /// 
 75         /// The error tips back color
 76         /// 
 77         private Color errorTipsBackColor = Color.FromArgb(255, 77, 58);
 78 
 79         /// 
 80         /// Gets or sets the color of the error tips back.
 81         /// 
 82         /// The color of the error tips back.
 83         [Browsable(true), Category("自定义属性"), Description("错误提示背景色"), Localizable(true)]
 84         public Color ErrorTipsBackColor
 85         {
 86             get { return errorTipsBackColor; }
 87             set { errorTipsBackColor = value; }
 88         }
 89 
 90         /// 
 91         /// The error tips fore color
 92         /// 
 93         private Color errorTipsForeColor = Color.White;
 94 
 95         /// 
 96         /// Gets or sets the color of the error tips fore.
 97         /// 
 98         /// The color of the error tips fore.
 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         /// 
108         /// Initializes a new instance of the  class.
109         /// 
110         public VerificationComponent()
111         {
112 
113         }
114 
115         /// 
116         /// Initializes a new instance of the  class.
117         /// 
118         /// The container.
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         /// 
128         /// 指定此对象是否可以将其扩展程序属性提供给指定的对象。
129         /// 
130         /// 要接收扩展程序属性的 
131         /// 如果此对象可以扩展程序属性提供给指定对象,则为 true;否则为 false。
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         /// 
144         /// Gets the verification model.
145         /// 
146         /// The control.
147         /// VerificationModel.
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         /// 
160         /// Sets the verification model.
161         /// 
162         /// The control.
163         /// The vm.
164         public void SetVerificationModel(Control control, VerificationModel vm)
165         {
166             m_controlCache[control] = vm;
167         }
168         #endregion
169 
170         #region 自定义正则    English:Custom Rules
171         /// 
172         /// Gets the verification custom regex.
173         /// 
174         /// The control.
175         /// System.String.
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         /// 
188         /// Sets the verification custom regex.
189         /// 
190         /// The control.
191         /// The string regex.
192         public void SetVerificationCustomRegex(Control control, string strRegex)
193         {
194             m_controlRegexCache[control] = strRegex;
195         }
196         #endregion
197 
198         #region 必填    English:Must fill
199         /// 
200         /// Gets the verification required.
201         /// 
202         /// The control.
203         /// true if XXXX, false otherwise.
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         /// 
213         /// Sets the verification required.
214         /// 
215         /// The control.
216         /// if set to true [BLN required].
217         public void SetVerificationRequired(Control control, bool blnRequired)
218         {
219             m_controlRequiredCache[control] = blnRequired;
220         }
221         #endregion
222 
223         #region 提示信息    English:Prompt information
224         /// 
225         /// Gets the verification error MSG.
226         /// 
227         /// The control.
228         /// System.String.
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         /// 
238         /// Sets the verification error MSG.
239         /// 
240         /// The control.
241         /// The string error MSG.
242         public void SetVerificationErrorMsg(Control control, string strErrorMsg)
243         {
244             m_controlMsgCache[control] = strErrorMsg;
245         }
246         #endregion
247 
248 
249         #region 验证    English:Verification
250         /// 
251         /// 功能描述:验证    English:Verification result processing
252         /// 作  者:HZH
253         /// 创建日期:2019-09-28 09:02:49
254         /// 任务编号:POS
255         /// 
256         /// c
257         /// 返回值
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         /// 
381         /// 功能描述:验证    English:Verification
382         /// 作  者:HZH
383         /// 创建日期:2019-09-27 17:54:38
384         /// 任务编号:POS
385         /// 
386         /// 返回值
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         /// 
406         /// 功能描述:验证结果处理    English:Verification result processing
407         /// 作  者:HZH
408         /// 创建日期:2019-09-27 17:54:59
409         /// 任务编号:POS
410         /// 
411         /// e
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 }

最后的话

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