1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Diagnostics; 5 using System.Linq; 6 using System.Text; 7 using System.Windows.Forms; 8 using System.Drawing; 9 using System.Text.RegularExpressions; 10 11 namespace FJZControl 12 { 13 public partial class FJZTextBox :TextBox 14 { 15 public FJZTextBox() 16 { 17 InitializeComponent(); 18 this.BorderStyle = BorderStyle.FixedSingle; 19 20 } 21 22 public FJZTextBox(IContainer container) 23 { 24 container.Add(this); 25 26 InitializeComponent(); 27 } 28 29 #region 屬性 30 private string regularExpress; 31 private string errorMsg; 32 [Category("FJZ的TextBox自定義控件屬性")] 33 [Description("須要驗證的正則表達式")] 34 public string RegularExpress 35 { 36 get 37 { 38 return regularExpress; 39 } 40 41 set 42 { 43 regularExpress = value; 44 } 45 } 46 [Category("FJZ的TextBox自定義控件屬性")] 47 [Description("驗證提示的錯誤信息")] 48 public string ErrorMsg 49 { 50 get 51 { 52 return errorMsg; 53 } 54 55 set 56 { 57 errorMsg = value; 58 } 59 } 60 61 #endregion 62 //擴展一個非空驗證的功能 63 private int BeginCheckEmpty() 64 { 65 if (this.Text.Trim().Length == 0) 66 { 67 errorProvider.SetError(this, "必填項不能爲空"); 68 return 0;//0表明驗證不經過 69 } 70 else 71 { 72 errorProvider.SetError(this, string.Empty);//清除小圓點的提示 73 return 1; 74 } 75 } 76 77 /// <summary> 78 /// 通用正則表達式驗證(能夠實現很是複雜的數據格式驗證) 79 /// </summary> 80 /// <param name="regularExpress">正則表達式</param> 81 /// <param name="errorMsg">錯誤信息</param> 82 /// <returns></returns> 83 public int BeginCommonValidate() 84 { 85 if (BeginCheckEmpty() == 0) return 0;//若是爲零,直接返回 86 //建立正則表達式對象 87 Regex regex = new Regex(this.regularExpress); 88 if (regex.IsMatch(this.Text.Trim())) 89 { 90 this.errorProvider.SetError(this, string.Empty); 91 return 1; 92 } 93 else 94 { 95 this.errorProvider.SetError(this, this.errorMsg); 96 return 0; 97 98 } 99 100 } 101 } 102 }