c# 校驗文本框的正則

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#region 經常使用數據驗證的封裝,數字字符的驗證
        /// <summary>
        /// 經常使用數據驗證的封裝,數字字符的驗證
        /// </summary>
        /// <param name="inputVal">須要驗證的數值【字符串,或者數字】</param>
        /// <param name="type">類型爲哪個驗證</param>
        /// <returns>若是驗證成功則返回True,不然返回false</returns>
        public static bool IsMatch( string inputVal, int type)
        {
            switch (type)
            {
                case 0:
                    return Regex.IsMatch(inputVal, @"^[1-9]d*$" );  //匹配正整數
                case 1:
                    return Regex.IsMatch(inputVal, @"^-?\d+$" );  //匹配整數
                case 2:
                    return Regex.IsMatch(inputVal, @"^[A-Za-z0-9]+$" );  //匹配由數字和26個英文字母組成的字符串
                case 3:
                    return Regex.IsMatch(inputVal, @"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$" );  //匹配正浮點數
                case 4:
                    return Regex.IsMatch(inputVal, @"^[\u4e00-\u9fa5]{0,}$" );  //匹配漢字
                case 5:
                    return Regex.IsMatch(inputVal, @"^[0-9]+(.[0-9]{1,3})?$" );  //匹配1~3位小數的正實數
                case 6:
                    return Regex.IsMatch(inputVal, @"^[A-Za-z]+$" );  //匹配英文字符
                case 7:
                    return Regex.IsMatch(inputVal, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" );   //驗證郵箱
                case 8:
                    return Regex.IsMatch(inputVal, @"((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)" );   //驗證手機號碼
                default :
                    return true ;
            }
        }
        #endregion
相關文章
相關標籤/搜索