(七十六)c#Winform自定义控件-表单验证组件
官网
前提
入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章。
GitHub:https://github.com/kwwwvagaa/NetWinformControl
码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
如果觉得写的还行,请点个 star 支持一下吧
欢迎前来交流探讨: 企鹅群568015492
来都来了,点个【推荐】再走吧,谢谢
NuGet
Install-Package HZH_Controls
目录
https://www.cnblogs.com/bfyx/p/11364884.html
用处及效果
准备工作
思路如下:
1、确定哪些控件需要进行验证,在组件中进行属性扩展
2、定义验证规则
3、根据验证规则的正则表达式进行验证和非空验证
4、触发验证结果事件
5、进行验证结果提示
开始
添加一个验证规则枚举
/// <summary>
/// 验证规则
/// </summary>
public enum VerificationModel
{
/// <summary>
/// 无
/// </summary>
[Description("无"), VerificationAttribute()]
None = ,
/// <summary>
/// 任意字母数字下划线
/// </summary>
[Description("任意字母数字下划线"), VerificationAttribute(@"^[a-zA-Z_0-1]*$", "请输入任意字母数字下划线")]
AnyChar = ,
/// <summary>
/// 任意数字
/// </summary>
[Description("任意数字"), VerificationAttribute(@"^[\-\+]?\d+(\.\d+)?$", "请输入任意数字")]
Number = ,
/// <summary>
/// 非负数
/// </summary>
[Description("非负数"), VerificationAttribute(@"^(\+)?\d+(\.\d+)?$", "请输入非负数")]
UnsignNumber = ,
/// <summary>
/// 正数
/// </summary>
[Description("正数"), VerificationAttribute(@"(\+)?([1-9][0-9]*(\.\d{1,2})?)|(0\.\d{1,2})", "请输入正数")]
PositiveNumber = ,
/// <summary>
/// 整数
/// </summary>
[Description("整数"), VerificationAttribute(@"^[\+\-]?\d+$", "请输入整数")]
Integer = ,
/// <summary>
/// 非负整数
/// </summary>
[Description("非负整数"), VerificationAttribute(@"^(\+)?\d+$", "请输入非负整数")]
UnsignIntegerNumber = ,
/// <summary>
/// 正整数
/// </summary>
[Description("正整数"), VerificationAttribute(@"^[0-9]*[1-9][0-9]*$", "请输入正整数")]
PositiveIntegerNumber = ,
/// <summary>
/// 邮箱
/// </summary>
[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)$", "请输入正确的邮箱地址")]
Email = ,
/// <summary>
/// 手机
/// </summary>
[Description("手机"), VerificationAttribute(@"^(\+?86)?1\d{10}$", "请输入正确的手机号")]
Phone = ,
/// <summary>
/// IP
/// </summary>
[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地址")]
IP = ,
/// <summary>
/// Url
/// </summary>
[Description("Url"), VerificationAttribute(@"^[a-zA-z]+://(//w+(-//w+)*)(//.(//w+(-//w+)*))*(//?//S*)?$", "请输入正确的网址")]
URL = ,
/// <summary>
/// 身份证号
/// </summary>
[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]$", "请输入正确的身份证号")]
IDCardNo = ,
/// <summary>
/// 正则验证
/// </summary>
[Description("自定义正则表达式"), VerificationAttribute()]
Custom = ,
}
还有一个验证规则枚举的特性
public class VerificationAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="VerificationAttribute"/> class.
/// </summary>
/// <param name="strRegex">The string regex.</param>
/// <param name="strErrorMsg">The string error MSG.</param>
public VerificationAttribute(string strRegex = "", string strErrorMsg = "")
{
Regex = strRegex;
ErrorMsg = strErrorMsg;
}
/// <summary>
/// Gets or sets the regex.
/// </summary>
/// <value>The regex.</value>
public string Regex { get; set; }
/// <summary>
/// Gets or sets the error MSG.
/// </summary>
/// <value>The error MSG.</value>
public string ErrorMsg { get; set; } }
定义事件参数
public class VerificationEventArgs : EventArgs
{
/// <summary>
/// Gets or sets the verification control.
/// </summary>
/// <value>The verification control.</value>
public Control VerificationControl { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [verify success].
/// </summary>
/// <value><c>true</c> if [verify success]; otherwise, <c>false</c>.</value>
public bool IsVerifySuccess { get; set; }
/// <summary>
/// Gets or sets the verification model.
/// </summary>
/// <value>The verification model.</value>
public VerificationModel VerificationModel { get; set; }
/// <summary>
/// 是否已处理,如果为true,则不再使用默认验证提示功能
/// </summary>
/// <value><c>true</c> if this instance is processed; otherwise, <c>false</c>.</value>
public bool IsProcessed { get; set; }
/// <summary>
/// Gets or sets 正则表达式
/// </summary>
/// <value>The custom regex.</value>
public string Regex { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="VerificationEventArgs"/> is required.
/// </summary>
/// <value><c>true</c> if required; otherwise, <c>false</c>.</value>
public bool Required { get; set; } /// <summary>
/// Gets or sets the error MSG.
/// </summary>
/// <value>The error MSG.</value>
public string ErrorMsg { get; set; }
}
添加一个类VerificationComponent继承Component,实现接口 IExtenderProvider以对控件进行扩展
定义属性
/// <summary>
/// Delegate VerificationedHandle
/// </summary>
/// <param name="e">The <see cref="VerificationEventArgs"/> instance containing the event data.</param>
public delegate void VerificationedHandle(VerificationEventArgs e);
/// <summary>
/// Occurs when [verificationed].
/// </summary>
[Browsable(true), Category("自定义属性"), Description("验证事件"), Localizable(true)]
public event VerificationedHandle Verificationed; /// <summary>
/// The m control cache
/// </summary>
Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>();
/// <summary>
/// The m control regex cache
/// </summary>
Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>();
/// <summary>
/// The m control required cache
/// </summary>
Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>();
/// <summary>
/// The m control MSG cache
/// </summary>
Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>();
/// <summary>
/// The m control tips
/// </summary>
Dictionary<Control, Forms.FrmAnchorTips> m_controlTips = new Dictionary<Control, Forms.FrmAnchorTips>(); /// <summary>
/// The error tips back color
/// </summary>
private Color errorTipsBackColor = Color.FromArgb(, , ); /// <summary>
/// Gets or sets the color of the error tips back.
/// </summary>
/// <value>The color of the error tips back.</value>
[Browsable(true), Category("自定义属性"), Description("错误提示背景色"), Localizable(true)]
public Color ErrorTipsBackColor
{
get { return errorTipsBackColor; }
set { errorTipsBackColor = value; }
} /// <summary>
/// The error tips fore color
/// </summary>
private Color errorTipsForeColor = Color.White; /// <summary>
/// Gets or sets the color of the error tips fore.
/// </summary>
/// <value>The color of the error tips fore.</value>
[Browsable(true), Category("自定义属性"), Description("错误提示文字颜色"), Localizable(true)]
public Color ErrorTipsForeColor
{
get { return errorTipsForeColor; }
set { errorTipsForeColor = value; }
}
哪些控件需要进行验证(属性扩展)
public bool CanExtend(object extendee)
{
if (extendee is TextBoxBase || extendee is UCTextBoxEx || extendee is ComboBox || extendee is UCCombox)
{
return true;
}
return false;
}
扩展属性
/// <summary>
/// The m control cache
/// </summary>
Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>();
/// <summary>
/// The m control regex cache
/// </summary>
Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>();
/// <summary>
/// The m control required cache
/// </summary>
Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>();
/// <summary>
/// The m control MSG cache
/// </summary>
Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>(); #region 验证规则 English:Validation rule
/// <summary>
/// Gets the verification model.
/// </summary>
/// <param name="control">The control.</param>
/// <returns>VerificationModel.</returns>
[Browsable(true), Category("自定义属性"), Description("验证规则"), DisplayName("VerificationModel"), Localizable(true)]
public VerificationModel GetVerificationModel(Control control)
{
if (m_controlCache.ContainsKey(control))
{
return m_controlCache[control];
}
else
return VerificationModel.None;
} /// <summary>
/// Sets the verification model.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="vm">The vm.</param>
public void SetVerificationModel(Control control, VerificationModel vm)
{
m_controlCache[control] = vm;
}
#endregion #region 自定义正则 English:Custom Rules
/// <summary>
/// Gets the verification custom regex.
/// </summary>
/// <param name="control">The control.</param>
/// <returns>System.String.</returns>
[Browsable(true), Category("自定义属性"), Description("自定义验证正则表达式"), DisplayName("VerificationCustomRegex"), Localizable(true)]
public string GetVerificationCustomRegex(Control control)
{
if (m_controlRegexCache.ContainsKey(control))
{
return m_controlRegexCache[control];
}
else
return "";
} /// <summary>
/// Sets the verification custom regex.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="strRegex">The string regex.</param>
public void SetVerificationCustomRegex(Control control, string strRegex)
{
m_controlRegexCache[control] = strRegex;
}
#endregion #region 必填 English:Must fill
/// <summary>
/// Gets the verification required.
/// </summary>
/// <param name="control">The control.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
[Browsable(true), Category("自定义属性"), Description("是否必填项"), DisplayName("VerificationRequired"), Localizable(true)]
public bool GetVerificationRequired(Control control)
{
if (m_controlRequiredCache.ContainsKey(control))
return m_controlRequiredCache[control];
return false;
} /// <summary>
/// Sets the verification required.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="blnRequired">if set to <c>true</c> [BLN required].</param>
public void SetVerificationRequired(Control control, bool blnRequired)
{
m_controlRequiredCache[control] = blnRequired;
}
#endregion #region 提示信息 English:Prompt information
/// <summary>
/// Gets the verification error MSG.
/// </summary>
/// <param name="control">The control.</param>
/// <returns>System.String.</returns>
[Browsable(true), Category("自定义属性"), Description("验证错误提示信息,当为空时则使用默认提示信息"), DisplayName("VerificationErrorMsg"), Localizable(true)]
public string GetVerificationErrorMsg(Control control)
{
if (m_controlMsgCache.ContainsKey(control))
return m_controlMsgCache[control];
return "";
} /// <summary>
/// Sets the verification error MSG.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="strErrorMsg">The string error MSG.</param>
public void SetVerificationErrorMsg(Control control, string strErrorMsg)
{
m_controlMsgCache[control] = strErrorMsg;
}
#endregion
验证处理
#region 验证 English:Verification
/// <summary>
/// 功能描述:验证 English:Verification result processing
/// 作 者:HZH
/// 创建日期:2019-09-28 09:02:49
/// 任务编号:POS
/// </summary>
/// <param name="c">c</param>
/// <returns>返回值</returns>
public bool Verification(Control c)
{
bool bln = true;
if (m_controlCache.ContainsKey(c))
{
var vm = m_controlCache[c];
string strRegex = "";
string strErrMsg = "";
#region 获取正则或默认错误提示 English:Get regular or error prompts
if (vm == VerificationModel.Custom)
{
//自定义正则
if (m_controlRegexCache.ContainsKey(c))
{
strRegex = m_controlRegexCache[c];
strErrMsg = "不正确的输入";
}
}
else
{
//获取默认正则和错误提示
Type type = vm.GetType(); //获取类型
MemberInfo[] memberInfos = type.GetMember(vm.ToString());
if (memberInfos.Length > )
{
var atts = memberInfos[].GetCustomAttributes(typeof(VerificationAttribute), false);
if (atts.Length > )
{
var va = ((VerificationAttribute)atts[]);
strErrMsg = va.ErrorMsg;
strRegex = va.Regex;
}
}
}
#endregion #region 取值 English:Value
string strValue = "";
if (c is TextBoxBase)
{
strValue = (c as TextBoxBase).Text;
}
else if (c is UCTextBoxEx)
{
strValue = (c as UCTextBoxEx).InputText;
}
else if (c is ComboBox)
{
var cbo = (c as ComboBox);
if (cbo.DropDownStyle == ComboBoxStyle.DropDownList)
{
strValue = cbo.SelectedItem == null ? "" : cbo.SelectedValue.ToString();
}
else
{
strValue = cbo.Text;
}
}
else if (c is UCCombox)
{
strValue = (c as UCCombox).SelectedText;
}
#endregion //自定义错误信息
if (m_controlMsgCache.ContainsKey(c) && !string.IsNullOrEmpty(m_controlMsgCache[c]))
strErrMsg = m_controlMsgCache[c]; //检查必填项
if (m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c])
{
if (string.IsNullOrEmpty(strValue))
{
VerControl(new VerificationEventArgs()
{
VerificationModel = vm,
Regex = strRegex,
ErrorMsg = "不能为空",
IsVerifySuccess = false,
Required = true,
VerificationControl = c
});
bln = false;
return false;
}
}
//验证正则
if (!string.IsNullOrEmpty(strValue))
{
if (!string.IsNullOrEmpty(strRegex))
{
if (!Regex.IsMatch(strValue, strRegex))
{
VerControl(new VerificationEventArgs()
{
VerificationModel = vm,
Regex = strRegex,
ErrorMsg = strErrMsg,
IsVerifySuccess = false,
Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],
VerificationControl = c
});
bln = false;
return false;
}
}
}
//没有问题出发一个成功信息
VerControl(new VerificationEventArgs()
{
VerificationModel = vm,
Regex = strRegex,
ErrorMsg = strErrMsg,
IsVerifySuccess = true,
Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],
VerificationControl = c
});
}
return bln;
}
#endregion
#region 验证 English:Verification
/// <summary>
/// 功能描述:验证 English:Verification
/// 作 者:HZH
/// 创建日期:2019-09-27 17:54:38
/// 任务编号:POS
/// </summary>
/// <returns>返回值</returns>
public bool Verification()
{
bool bln = true;
foreach (var item in m_controlCache)
{
Control c = item.Key;
if (!Verification(c))
{
bln = false;
}
}
return bln;
}
#endregion #region 验证结果处理 English:Verification result processing
/// <summary>
/// 功能描述:验证结果处理 English:Verification result processing
/// 作 者:HZH
/// 创建日期:2019-09-27 17:54:59
/// 任务编号:POS
/// </summary>
/// <param name="e">e</param>
private void VerControl(VerificationEventArgs e)
{
//如果成功则移除失败提示
if (e.IsVerifySuccess)
{
if (m_controlTips.ContainsKey(e.VerificationControl))
{
m_controlTips[e.VerificationControl].Close();
m_controlTips.Remove(e.VerificationControl);
}
}
//触发事件
if (Verificationed != null)
{
Verificationed(e);
if (e.IsProcessed)//如果已处理,则不再向下执行
{
return;
}
}
//如果失败则显示提示
if (!e.IsVerifySuccess)
{
if (m_controlTips.ContainsKey(e.VerificationControl))
{
m_controlTips[e.VerificationControl].StrMsg = e.ErrorMsg;
}
else
{
var tips = Forms.FrmAnchorTips.ShowTips(e.VerificationControl, e.ErrorMsg, background: errorTipsBackColor, foreColor: errorTipsForeColor, autoCloseTime: , blnTopMost: false);
m_controlTips[e.VerificationControl] = tips;
}
}
}
#endregion
完整代码
// ***********************************************************************
// Assembly : HZH_Controls
// Created : 2019-09-27
//
// ***********************************************************************
// <copyright file="VerificationComponent.cs">
// Copyright by Huang Zhenghui(黄正辉) All, QQ group:568015492 QQ:623128629 Email:623128629@qq.com
// </copyright>
//
// Blog: https://www.cnblogs.com/bfyx
// GitHub:https://github.com/kwwwvagaa/NetWinformControl
// gitee:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
//
// If you use this code, please keep this note.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms; namespace HZH_Controls.Controls
{
/// <summary>
/// Class VerificationComponent.
/// Implements the <see cref="System.ComponentModel.Component" />
/// Implements the <see cref="System.ComponentModel.IExtenderProvider" />
/// </summary>
/// <seealso cref="System.ComponentModel.Component" />
/// <seealso cref="System.ComponentModel.IExtenderProvider" />
[ProvideProperty("VerificationModel", typeof(Control))]
[ProvideProperty("VerificationCustomRegex", typeof(Control))]
[ProvideProperty("VerificationRequired", typeof(Control))]
[ProvideProperty("VerificationErrorMsg", typeof(Control))]
[DefaultEvent("Verificationed")]
public class VerificationComponent : Component, IExtenderProvider
{
/// <summary>
/// Delegate VerificationedHandle
/// </summary>
/// <param name="e">The <see cref="VerificationEventArgs"/> instance containing the event data.</param>
public delegate void VerificationedHandle(VerificationEventArgs e);
/// <summary>
/// Occurs when [verificationed].
/// </summary>
[Browsable(true), Category("自定义属性"), Description("验证事件"), Localizable(true)]
public event VerificationedHandle Verificationed; /// <summary>
/// The m control cache
/// </summary>
Dictionary<Control, VerificationModel> m_controlCache = new Dictionary<Control, VerificationModel>();
/// <summary>
/// The m control regex cache
/// </summary>
Dictionary<Control, string> m_controlRegexCache = new Dictionary<Control, string>();
/// <summary>
/// The m control required cache
/// </summary>
Dictionary<Control, bool> m_controlRequiredCache = new Dictionary<Control, bool>();
/// <summary>
/// The m control MSG cache
/// </summary>
Dictionary<Control, string> m_controlMsgCache = new Dictionary<Control, string>();
/// <summary>
/// The m control tips
/// </summary>
Dictionary<Control, Forms.FrmAnchorTips> m_controlTips = new Dictionary<Control, Forms.FrmAnchorTips>(); /// <summary>
/// The error tips back color
/// </summary>
private Color errorTipsBackColor = Color.FromArgb(, , ); /// <summary>
/// Gets or sets the color of the error tips back.
/// </summary>
/// <value>The color of the error tips back.</value>
[Browsable(true), Category("自定义属性"), Description("错误提示背景色"), Localizable(true)]
public Color ErrorTipsBackColor
{
get { return errorTipsBackColor; }
set { errorTipsBackColor = value; }
} /// <summary>
/// The error tips fore color
/// </summary>
private Color errorTipsForeColor = Color.White; /// <summary>
/// Gets or sets the color of the error tips fore.
/// </summary>
/// <value>The color of the error tips fore.</value>
[Browsable(true), Category("自定义属性"), Description("错误提示文字颜色"), Localizable(true)]
public Color ErrorTipsForeColor
{
get { return errorTipsForeColor; }
set { errorTipsForeColor = value; }
} #region 构造函数 English:Constructor
/// <summary>
/// Initializes a new instance of the <see cref="VerificationComponent"/> class.
/// </summary>
public VerificationComponent()
{ } /// <summary>
/// Initializes a new instance of the <see cref="VerificationComponent"/> class.
/// </summary>
/// <param name="container">The container.</param>
public VerificationComponent(IContainer container)
: this()
{
container.Add(this);
}
#endregion #region 指定此对象是否可以将其扩展程序属性提供给指定的对象。 English:Specifies whether this object can provide its extender properties to the specified object.
/// <summary>
/// 指定此对象是否可以将其扩展程序属性提供给指定的对象。
/// </summary>
/// <param name="extendee">要接收扩展程序属性的 <see cref="T:System.Object" />。</param>
/// <returns>如果此对象可以扩展程序属性提供给指定对象,则为 true;否则为 false。</returns>
public bool CanExtend(object extendee)
{
if (extendee is TextBoxBase || extendee is UCTextBoxEx || extendee is ComboBox || extendee is UCCombox)
{
return true;
}
return false;
}
#endregion #region 验证规则 English:Validation rule
/// <summary>
/// Gets the verification model.
/// </summary>
/// <param name="control">The control.</param>
/// <returns>VerificationModel.</returns>
[Browsable(true), Category("自定义属性"), Description("验证规则"), DisplayName("VerificationModel"), Localizable(true)]
public VerificationModel GetVerificationModel(Control control)
{
if (m_controlCache.ContainsKey(control))
{
return m_controlCache[control];
}
else
return VerificationModel.None;
} /// <summary>
/// Sets the verification model.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="vm">The vm.</param>
public void SetVerificationModel(Control control, VerificationModel vm)
{
m_controlCache[control] = vm;
}
#endregion #region 自定义正则 English:Custom Rules
/// <summary>
/// Gets the verification custom regex.
/// </summary>
/// <param name="control">The control.</param>
/// <returns>System.String.</returns>
[Browsable(true), Category("自定义属性"), Description("自定义验证正则表达式"), DisplayName("VerificationCustomRegex"), Localizable(true)]
public string GetVerificationCustomRegex(Control control)
{
if (m_controlRegexCache.ContainsKey(control))
{
return m_controlRegexCache[control];
}
else
return "";
} /// <summary>
/// Sets the verification custom regex.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="strRegex">The string regex.</param>
public void SetVerificationCustomRegex(Control control, string strRegex)
{
m_controlRegexCache[control] = strRegex;
}
#endregion #region 必填 English:Must fill
/// <summary>
/// Gets the verification required.
/// </summary>
/// <param name="control">The control.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
[Browsable(true), Category("自定义属性"), Description("是否必填项"), DisplayName("VerificationRequired"), Localizable(true)]
public bool GetVerificationRequired(Control control)
{
if (m_controlRequiredCache.ContainsKey(control))
return m_controlRequiredCache[control];
return false;
} /// <summary>
/// Sets the verification required.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="blnRequired">if set to <c>true</c> [BLN required].</param>
public void SetVerificationRequired(Control control, bool blnRequired)
{
m_controlRequiredCache[control] = blnRequired;
}
#endregion #region 提示信息 English:Prompt information
/// <summary>
/// Gets the verification error MSG.
/// </summary>
/// <param name="control">The control.</param>
/// <returns>System.String.</returns>
[Browsable(true), Category("自定义属性"), Description("验证错误提示信息,当为空时则使用默认提示信息"), DisplayName("VerificationErrorMsg"), Localizable(true)]
public string GetVerificationErrorMsg(Control control)
{
if (m_controlMsgCache.ContainsKey(control))
return m_controlMsgCache[control];
return "";
} /// <summary>
/// Sets the verification error MSG.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="strErrorMsg">The string error MSG.</param>
public void SetVerificationErrorMsg(Control control, string strErrorMsg)
{
m_controlMsgCache[control] = strErrorMsg;
}
#endregion #region 验证 English:Verification
/// <summary>
/// 功能描述:验证 English:Verification result processing
/// 作 者:HZH
/// 创建日期:2019-09-28 09:02:49
/// 任务编号:POS
/// </summary>
/// <param name="c">c</param>
/// <returns>返回值</returns>
public bool Verification(Control c)
{
bool bln = true;
if (m_controlCache.ContainsKey(c))
{
var vm = m_controlCache[c];
string strRegex = "";
string strErrMsg = "";
#region 获取正则或默认错误提示 English:Get regular or error prompts
if (vm == VerificationModel.Custom)
{
//自定义正则
if (m_controlRegexCache.ContainsKey(c))
{
strRegex = m_controlRegexCache[c];
strErrMsg = "不正确的输入";
}
}
else
{
//获取默认正则和错误提示
Type type = vm.GetType(); //获取类型
MemberInfo[] memberInfos = type.GetMember(vm.ToString());
if (memberInfos.Length > )
{
var atts = memberInfos[].GetCustomAttributes(typeof(VerificationAttribute), false);
if (atts.Length > )
{
var va = ((VerificationAttribute)atts[]);
strErrMsg = va.ErrorMsg;
strRegex = va.Regex;
}
}
}
#endregion #region 取值 English:Value
string strValue = "";
if (c is TextBoxBase)
{
strValue = (c as TextBoxBase).Text;
}
else if (c is UCTextBoxEx)
{
strValue = (c as UCTextBoxEx).InputText;
}
else if (c is ComboBox)
{
var cbo = (c as ComboBox);
if (cbo.DropDownStyle == ComboBoxStyle.DropDownList)
{
strValue = cbo.SelectedItem == null ? "" : cbo.SelectedValue.ToString();
}
else
{
strValue = cbo.Text;
}
}
else if (c is UCCombox)
{
strValue = (c as UCCombox).SelectedText;
}
#endregion //自定义错误信息
if (m_controlMsgCache.ContainsKey(c) && !string.IsNullOrEmpty(m_controlMsgCache[c]))
strErrMsg = m_controlMsgCache[c]; //检查必填项
if (m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c])
{
if (string.IsNullOrEmpty(strValue))
{
VerControl(new VerificationEventArgs()
{
VerificationModel = vm,
Regex = strRegex,
ErrorMsg = "不能为空",
IsVerifySuccess = false,
Required = true,
VerificationControl = c
});
bln = false;
return false;
}
}
//验证正则
if (!string.IsNullOrEmpty(strValue))
{
if (!string.IsNullOrEmpty(strRegex))
{
if (!Regex.IsMatch(strValue, strRegex))
{
VerControl(new VerificationEventArgs()
{
VerificationModel = vm,
Regex = strRegex,
ErrorMsg = strErrMsg,
IsVerifySuccess = false,
Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],
VerificationControl = c
});
bln = false;
return false;
}
}
}
//没有问题出发一个成功信息
VerControl(new VerificationEventArgs()
{
VerificationModel = vm,
Regex = strRegex,
ErrorMsg = strErrMsg,
IsVerifySuccess = true,
Required = m_controlRequiredCache.ContainsKey(c) && m_controlRequiredCache[c],
VerificationControl = c
});
}
return bln;
}
#endregion
#region 验证 English:Verification
/// <summary>
/// 功能描述:验证 English:Verification
/// 作 者:HZH
/// 创建日期:2019-09-27 17:54:38
/// 任务编号:POS
/// </summary>
/// <returns>返回值</returns>
public bool Verification()
{
bool bln = true;
foreach (var item in m_controlCache)
{
Control c = item.Key;
if (!Verification(c))
{
bln = false;
}
}
return bln;
}
#endregion #region 验证结果处理 English:Verification result processing
/// <summary>
/// 功能描述:验证结果处理 English:Verification result processing
/// 作 者:HZH
/// 创建日期:2019-09-27 17:54:59
/// 任务编号:POS
/// </summary>
/// <param name="e">e</param>
private void VerControl(VerificationEventArgs e)
{
//如果成功则移除失败提示
if (e.IsVerifySuccess)
{
if (m_controlTips.ContainsKey(e.VerificationControl))
{
m_controlTips[e.VerificationControl].Close();
m_controlTips.Remove(e.VerificationControl);
}
}
//触发事件
if (Verificationed != null)
{
Verificationed(e);
if (e.IsProcessed)//如果已处理,则不再向下执行
{
return;
}
}
//如果失败则显示提示
if (!e.IsVerifySuccess)
{
if (m_controlTips.ContainsKey(e.VerificationControl))
{
m_controlTips[e.VerificationControl].StrMsg = e.ErrorMsg;
}
else
{
var tips = Forms.FrmAnchorTips.ShowTips(e.VerificationControl, e.ErrorMsg, background: errorTipsBackColor, foreColor: errorTipsForeColor, autoCloseTime: , blnTopMost: false);
m_controlTips[e.VerificationControl] = tips;
}
}
}
#endregion
}
}
最后的话
如果你喜欢的话,请到 https://gitee.com/kwwwvagaa/net_winform_custom_control 点个星星吧
(七十六)c#Winform自定义控件-表单验证组件的更多相关文章
- Form表单验证组件
Tyrion是一个基于Python实现的支持多个WEB框架的Form表单验证组件,其完美的支持Tornado.Django.Flask.Bottle Web框架.Tyrion主要有两大重要动能: 表单 ...
- BootstrapBlazor-ValidateForm 表单验证组件
原文链接:https://www.cnblogs.com/ysmc/p/16082279.html 故名思意,这个组件的作用我就不再多说了,配合 AutoGenerateColumnAttribute ...
- jQuery表单验证组件BootstrapValidator
github:https://github.com/nghuuphuoc/bootstrapvalidator 参考博客:JS组件系列——Form表单验证神器: BootstrapValidator ...
- (七十)c#Winform自定义控件-饼状图
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kwwwvagaa/NetWinformControl 码云:ht ...
- Html学习之十六(表格与表单学习--课程表制作)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 测开之路一百四十六:WTForms之表单应用
WTForms主要是两个功能:1.生成HTML标签 2.对数据格式进行验证 官网:https://wtforms.readthedocs.io/en/stable/ 这篇介绍用wtform生成htm ...
- vee-validate表单验证组件
vee-validate是VUE的基于模板的验证框架,允许您验证输入并显示错误 安装 npm i vee-validate --save 引入 import Vue from 'vue'; impor ...
- jQuery html5Validate基于HTML5表单验证插件
更新于2016-02-25 前面提到的新版目前线上已经可以访问: http://mp.gtimg.cn/old_mp/assets/js/common/ui/Validate.js demo体验狠狠地 ...
- 第三百七十六节,Django+Xadmin打造上线标准的在线教育平台—创建用户操作app,在models.py文件生成5张表,用户咨询表、课程评论表、用户收藏表、用户消息表、用户学习表
第三百七十六节,Django+Xadmin打造上线标准的在线教育平台—创建用户操作app,在models.py文件生成5张表,用户咨询表.课程评论表.用户收藏表.用户消息表.用户学习表 创建名称为ap ...
随机推荐
- Mybatis的一级缓存和二级缓存的理解以及用法
程序中为什么使用缓存? 先了解一下缓存的概念:原始意义是指访问速度比一般随机存取存储器快的一种RAM,通常它不像系统主存那样使用DRAM技术,而使用昂贵但较快速的SRAM技术.对于我们编程来说,所谓的 ...
- Spring学习之旅(六)--SpringMVC集成
对大多数 Java 开发来说,基于 web 的应用程序是我们主要的关注点. Spring 也提供了对于 web 的支持,基于 MVC 模式的 Spring MVC 能够帮助我们灵活和松耦合的完成 we ...
- 详解javascript中的this的指向问题
首先,要明白this 既不指向函数自身,也不指函数的词法作用域.this一般存在于函数中,表示当前函数的执行上下文,如果函数没有执行,那么this没有内容,只有函数在执行后this才有绑定. 然后,我 ...
- 04_枚举类型iota
iota是枚举类型的关键字,使用iota可以方便快捷的给常量赋值,主要体现在以下几个方面:1.iota常量自动生成器,每个一行加12.iota给常量赋值使用3.iota遇到const重置为04.可以写 ...
- 解决npm报错:Module build failed: TypeError: this.getResolve is not a function
1.sass-loader的版本过高导致的编译错误,当前最高版本是8.x,需要退回到7.3.1 运行: npm uninstall sass-loader --save-dev(卸载当前版本) npm ...
- 【故障公告】升级阿里云 RDS SQL Server 实例故障经过
昨天晚上,我们使用的阿里云 RDS SQL Server 2008 R2 实例突然出现持续 CPU 100% 问题,后来我们通过重启实例恢复了正常(详见故障公告).但是在恢复正常后发现了新问题,这台 ...
- Codeforces Round #506 (Div. 3) 1029 D. Concatenated Multiples
题意: 给定n个数字,和一个模数k,从中选出两个数,直接拼接,问拼接成的数字是k的倍数的组合有多少个. 思路: 对于a,b两个数,假定len = length of (b),那么a,b满足条件就是a ...
- hihocoder #1617 : 方格取数(dp)
题目链接:http://hihocoder.com/problemset/problem/1617 题解:一道递推的dp题.这题显然可以考虑两个人同时从起点出发这样就不会重复了设dp[step][i] ...
- lightoj 1201 - A Perfect Murder(树形dp)
题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1201 题解:简单的树形dp,dp[0][i]表示以i为根结点不傻i的最多有多少 ...
- hdu 4614 Vases and Flowers(线段树)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4614 题意: 给你N个花瓶,编号是0 到 N - 1 ,初始状态花瓶是空的,每个花瓶最多插一朵花. ...