主頁 > .NET開發 > (七十六)c#Winform自定義控制元件-表單驗證組件-HZHControls

(七十六)c#Winform自定義控制元件-表單驗證組件-HZHControls

2020-09-11 08:22:47 .NET開發

官網

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         /// IP58         /// </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         /// Url63         /// </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 cache14         /// </summary>15         Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>();16         /// <summary>17         /// The m control regex cache18         /// </summary>19         Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>();20         /// <summary>21         /// The m control required cache22         /// </summary>23         Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>();24         /// <summary>25         /// The m control MSG cache26         /// </summary>27         Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>();28         /// <summary>29         /// The m control tips30         /// </summary>31         Dictionary<Control, Forms.FrmAnchorTips> m_controlTips = new Dictionary<Control, Forms.FrmAnchorTips>();32 33         /// <summary>34         /// The error tips back color35         /// </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 ErrorTipsBackColor44         {45             get { return errorTipsBackColor; }46             set { errorTipsBackColor = value; }47         }48 49         /// <summary>50         /// The error tips fore color51         /// </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 ErrorTipsForeColor60         {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 information100         /// <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 = https://www.cnblogs.com/bfyx/p/""; 48                 if (c is TextBoxBase) 49                 { 50                     strValue = https://www.cnblogs.com/bfyx/p/(c as TextBoxBase).Text; 51                 } 52                 else if (c is UCTextBoxEx) 53                 { 54                     strValue = https://www.cnblogs.com/bfyx/p/(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 = https://www.cnblogs.com/bfyx/p/cbo.SelectedItem == null ? "" : cbo.SelectedValue.ToString(); 62                     } 63                     else 64                     { 65                         strValue =https://www.cnblogs.com/bfyx/p/ cbo.Text; 66                     } 67                 } 68                 else if (c is UCCombox) 69                 { 70                     strValue = https://www.cnblogs.com/bfyx/p/(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 = c111                             });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 = c126                 });127             }128             return bln;129         }130         #endregion131         #region 驗證    English:Verification132         /// <summary>133         /// 功能描述:驗證    English:Verification134         /// 作  者:HZH135         /// 創建日期:2019-09-27 17:54:38136         /// 任務編號:POS137         /// </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         #endregion153 154 155 156         #region 驗證結果處理    English:Verification result processing157         /// <summary>158         /// 功能描述:驗證結果處理    English:Verification result processing159         /// 作  者:HZH160         /// 創建日期:2019-09-27 17:54:59161         /// 任務編號:POS162         /// </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                 else192                 {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:[email protected]  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 ErrorTipsForeColor101         {102             get { return errorTipsForeColor; }103             set { errorTipsForeColor = value; }104         }105 106         #region 建構式    English:Constructor107         /// <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         #endregion125 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         #endregion141 142         #region 驗證規則    English:Validation rule143         /// <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             else156                 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         #endregion169 170         #region 自定義正則    English:Custom Rules171         /// <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             else184                 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         #endregion197 198         #region 必填    English:Must fill199         /// <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         #endregion222 223         #region 提示資訊    English:Prompt information224         /// <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         #endregion247 248 249         #region 驗證    English:Verification250         /// <summary>251         /// 功能描述:驗證    English:Verification result processing252         /// 作  者:HZH253         /// 創建日期:2019-09-28 09:02:49254         /// 任務編號:POS255         /// </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 prompts267                 if (vm == VerificationModel.Custom)268                 {269                     //自定義正則270                     if (m_controlRegexCache.ContainsKey(c))271                     {272                         strRegex = m_controlRegexCache[c];273                         strErrMsg = "不正確的輸入";274                     }275                 }276                 else277                 {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                 #endregion293 294                 #region 取值    English:Value295                 string strValue = https://www.cnblogs.com/bfyx/p/"";296                 if (c is TextBoxBase)297                 {298                     strValue = https://www.cnblogs.com/bfyx/p/(c as TextBoxBase).Text;299                 }300                 else if (c is UCTextBoxEx)301                 {302                     strValue = https://www.cnblogs.com/bfyx/p/(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 = https://www.cnblogs.com/bfyx/p/cbo.SelectedItem == null ? "" : cbo.SelectedValue.ToString();310                     }311                     else312                     {313                         strValue =https://www.cnblogs.com/bfyx/p/ cbo.Text;314                     }315                 }316                 else if (c is UCCombox)317                 {318                     strValue = https://www.cnblogs.com/bfyx/p/(c as UCCombox).SelectedText;319                 }320                 #endregion321 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 = c339                         });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 = c359                             });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 = c374                 });375             }376             return bln;377         }378         #endregion379         #region 驗證    English:Verification380         /// <summary>381         /// 功能描述:驗證    English:Verification382         /// 作  者:HZH383         /// 創建日期:2019-09-27 17:54:38384         /// 任務編號:POS385         /// </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         #endregion401 402 403 404         #region 驗證結果處理    English:Verification result processing405         /// <summary>406         /// 功能描述:驗證結果處理    English:Verification result processing407         /// 作  者:HZH408         /// 創建日期:2019-09-27 17:54:59409         /// 任務編號:POS410         /// </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                 else440                 {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         #endregion447     }448 }
View Code

 

最后的話

如果你喜歡的話,請到 https://gitee.com/kwwwvagaa/net_winform_custom_control 點個星星吧

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/4898.html

標籤:WinForm

上一篇:(七十五)c#Winform自定義控制元件-控制元件水印組件-HZHControls

下一篇:(七十七)c#Winform自定義控制元件-采樣控制元件-HZHControls

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more