C#用正则表达式验证格式:电话号码、密码、邮编、手机号码、身份证、指定的小数点后位数、有效月、有效日

news2024/9/20 18:48:06

        正则表达式在程序设计中有着重要的位置,经常被用于处理字符串信息。

        用Regex类的IsMatch方法,使用正则表达式可以验证电话号码是否合法。

一、涉及到的知识点

        Regex类的IsMatch方法用于指示正则表达式使用pattern参数中指定的正则表达式是否在输入字符串中找到匹配项。语法格式如下:

public static bool IsMatch(string input,string patterm)

参数说明
Input:字符串对象,表示要搜索匹配项的字符串。
Pattern:字符串对象,表示要匹配的正则表达式模式。
Bool:返回布尔值,如果正则表达式找到匹配项,则返回值为true,否则返回值为false。

        其中,正则表达式中匹配位置的元字符“^”。正则表达式中“^”用于匹配行首,如果正则表达式匹配以First开头的行,则正则表达式如下:^First。

        如果电话号码的格式:xxx-xxxxxxxx,其中,x—代表数字,那么匹配的正则表达式是:^(\d{3,4}-)?\d{6,8}$。

        如果密码有a-z、A-Z、0-9组成,并且至少一个大小写字母数字,那么其正则表达式:[A-Za-z]+[0-9];

        如果密码有a-z、A-Z、0-9组成,并且至少一个大小写字母数字,那么其正则表达式:[A-Za-z0-9]+,其中+有没有都可以;

        如果把正则表达式改为[A-Z]+[a-z]+[0-9],就变成依次至少一个大写、一个小写、一个数字了,打乱了顺序都不行。

        由6位数字组成的邮编的正则表达式:^\d{6}$;

        手机号码由11位数字组成,以1开头、第二位数字为3,4,5,6,7,8,9中一个、第三位到十一位数字为0到9的任意一个数字,其正则表达式:^1[3-9]\d{9}$;

        18位身份号码是特征组合码,由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位校验码。其中:

  • 地址码:表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。其中前两位为省份编码。
  • 出生日期码:表示编码对象出生的年、月、日,按GB/T7408的规定执行,格式如20240130,之间不用分隔符。
  • 顺序码:表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配给女性。
  • 校验码计算方式:

        (1)对前17位数字本体码加权求和公式为:S = Sum(Ai * Wi), i = 1, ... , 17。其中Ai表示第i位置上的身份证号码数值;Wi表示第i位置上的加权因子,按位置依次为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2;
        (2)以11对计算结果取模:Y = mod(S, 11);
        (3)根据模的值得到对应的校验码,对应关系为:
             Y值:0 1 2 3 4 5 6 7 8 9 10
        校验码:1 0 X 9 8 7 6 5 4 3 2

        身份证号正则表达式:

//闰年
^[1-9]\d{5}(19|20)\d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2]\d|3[0-1])|(04|06|09|11)(0[1-9]|[1-2]\d|30)|02(0[1-9]|[1-2]\d))\d{3}[\dXx]$
//平年
^[1-9]\d{5}(19|20)\d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2]\d|3[0-1])|(04|06|09|11)(0[1-9]|[1-2]\d|30)|02(0[1-9]|1\d|2[0-8]))\d{3}[\dXx]$

         用正则表达式可以校验指定小数点后的位数是否匹配,比如验证小数点后位数是否2位的正则表达式:^[0-9]+(.\d{2})?$,^[0-9]+.\d{2}$,^[0-9]+\.\d{2}$,^[0-9]+\.[0-9]{2}$;

        验证输入的数值是否有效的月份的正则表达式:^(0?[[1-9]1[0-2]]$,其中0?表示匹配零个或1个“0”,[1-9]表示匹配数字1~9,1[0-2]表示匹配数字10、11、12。

        验证输入的日期型字符串是否符合日期,需要判断是否是小月、大月、二月闰年、二月平年,因此需要用4个正则表达式才能正确表达任意的输入是否符合日期的规则;完整的正则表达式:小月"^((0?[1-9])|((1|2)[0-9])|30)$",大月"^((0?[1-9])|((1|2)[0-9])|30|31)$",润二月"^((0?[1-9])|((1|2)[0-9]))$",平二月"^((0?[1-9])|((1|2)[0-8]))$"。

        如果用DateTime.ParseExact方法验证输入的日期格式,不需要复杂的判断,简简单单就可以实现设计目的。

 

二、实例1:验证电话号码的格式

//使用正则表达式验证电话号码
namespace _070
{
    public partial class Form1 : Form
    {
        private Label? label1;
        private Label? label2;
        private Label? label3;
        private Button? button1;
        private TextBox? textBox1;
        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(36, 22),
                Name = "label1",
                Size = new Size(68, 17),
                TabIndex = 0,
                Text = "输入号码:"
            };
            // 
            // label2
            //        
            label2 = new Label
            {
                AutoSize = true,
                Location = new Point(156, 49),
                Name = "label2",
                Size = new Size(79, 17),
                TabIndex = 1,
                Text = "xxx-xxxxxxxx"
            };
            // 
            // label3
            //          
            label3 = new Label
            {
                AutoSize = true,
                Location = new Point(36, 49),
                Name = "label3",
                Size = new Size(68, 17),
                TabIndex = 2,
                Text = "号码格式:"
            };
            // 
            // button1
            //         
            button1 = new Button
            {
                Location = new Point(160, 76),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 3,
                Text = "号码验证",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(115, 16),
                Name = "textBox1",
                Size = new Size(120, 23),
                TabIndex = 4
            };
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(294, 111);
            Controls.Add(textBox1);
            Controls.Add(button1);
            Controls.Add(label3);
            Controls.Add(label2);
            Controls.Add(label1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "使用正则表达式验证电话号码";
          
        }
        /// <summary>
        /// 验证电话号码格式是否正确
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            if (!IsTelephone(textBox1!.Text))
            { 
                MessageBox.Show("电话号码格式不正确"); 
            }
            else 
            { 
                MessageBox.Show("电话号码格式正确"); 
            }
        }

        /// <summary>
        /// 验证电话号码格式是否匹配
        /// </summary>
        /// <param name="str_telephone">电话号码信息</param>
        /// <returns>方法返回布尔值</returns>
        public static bool IsTelephone(string str_telephone)
        {
            return MyRegex().IsMatch(str_telephone);
        }

        [System.Text.RegularExpressions.GeneratedRegex(@"^(\d{3,4}-)?\d{6,8}$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex();
    }
}

三、实例2:验证密码的格式

// 使用正则表达式验证密码格式
namespace _071
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Button? button1;
        private TextBox? textBox1;
        private Label? label1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(171, 58),
                Name = "button1",
                Size = new Size(100, 23),
                TabIndex = 2,
                Text = "验证密码格式",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // textBox1
            // 

            textBox1 = new TextBox
            {
                Location = new Point(126, 24),
                Name = "textBox1",
                Size = new Size(145, 23),
                TabIndex = 1
            };
            // 
            // label1
            //

            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(35, 30),
                Name = "label1",
                Size = new Size(68, 17),
                TabIndex = 0,
                Text = "输入密码:"
            };
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(307, 87),
                TabIndex = 0,
                TabStop = false,
                Text = "密码必须由数字和大小写字母组成"
            };
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();

            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(331, 111);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "正则表达式验证密码格式";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }

        private void Button1_Click(object? sender, EventArgs e)
        {
            if (!IsPassword(textBox1!.Text.Trim()))
            { 
                MessageBox.Show("密码格式不正确!!!"); 
            }
            else
            {
                MessageBox.Show("密码格式正确!!!!!");
            }
        }
        /// <summary>
        /// 验证码码输入条件
        /// </summary>
        /// <param name="str_password">密码字符串</param>
        /// <returns>返回布尔值</returns>
        public static bool IsPassword(string str_password)
        {
            return MyRegex().IsMatch(str_password);
        }

        [System.Text.RegularExpressions.GeneratedRegex(@"[A-Za-z]+[0-9]")]//至少有一个字母,至少有一个数字
        //[System.Text.RegularExpressions.GeneratedRegex(@"[A-Z]+[a-z]+[0-9]")]//依次至少有一个大写一个小写一个
        //[System.Text.RegularExpressions.GeneratedRegex(@"[A-Za-z0-9]+")]//至少一个
        private static partial System.Text.RegularExpressions.Regex MyRegex();
    }
}

四、实例3:验证邮编的格式

// 用正则表达式验证邮编合法性
namespace _072
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private TextBox? textBox1;
        private Button? button1;
        private Label? label1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(139, 32),
                Name = "textBox1",
                Size = new Size(100, 23),
                TabIndex = 2
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(139, 61),
                Name = "button1",
                Size = new Size(100, 23),
                TabIndex = 1,
                Text = "验证邮编",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(55, 35),
                Name = "label1",
                Size = new Size(68, 17),
                TabIndex = 0,
                Text = "输入邮编:"
            };
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(280, 98),
                TabIndex = 0,
                TabStop = false,
                Text = "验证邮编格式:"
            };
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(304, 122);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "验证邮编格式合法性";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }

        private void Button1_Click(object? sender, EventArgs e)
        {
            if (!IsPostalcode(textBox1!.Text))
            { 
                MessageBox.Show("邮政编号不正确!!!"); 
            }
            else 
            {
                MessageBox.Show("邮政编号正确!!!!!"); 
            }
        }
        /// <summary>
        /// 验证邮编格式是否正确
        /// </summary>
        /// <param name="str_postalcode">邮编字符串</param>
        /// <returns>返回布尔值</returns>
        public static bool IsPostalcode(string str_postalcode)
        {
            return MyRegex().IsMatch(str_postalcode);
        }

        [System.Text.RegularExpressions.GeneratedRegex(@"^\d{6}$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex();
    }
}

五、实例4:验证手机号码的格式

//用正则表达式验证手机号码合法性
namespace _073
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Button? button1;
        private TextBox? textBox1;
        private Label? label1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(129, 60),
                Name = "button1",
                Size = new Size(120, 23),
                TabIndex = 3,
                Text = "验证手机号码",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(129, 31),
                Name = "textBox1",
                Size = new Size(120, 23),
                TabIndex = 1
            };
            // 
            // label1
            //           
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(31, 37),
                Name = "label1",
                Size = new Size(92, 17),
                TabIndex = 0,
                Text = "输入手机号码:"
            };
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(280, 92),
                TabIndex = 0,
                TabStop = false,
                Text = "验证手机号码"
            };
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();
           
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(304, 122);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "验证手机号码合法性";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }

        private void Button1_Click(object? sender, EventArgs e)
        {
            if (!IsHandset(textBox1!.Text))
            { 
                MessageBox.Show("手机号不正确!!!"); 
            }
            else
            {
                MessageBox.Show("手机号正确!!!!!"); 
            }
        }
        /// <summary>
        /// 验证手机号是否正确
        /// </summary>
        /// <param name="str_handset">手机号码字符串</param>
        /// <returns>返回布尔值</returns>
        public static bool IsHandset(string str_handset)
        {
            return MyRegex().IsMatch(str_handset);
        }

        [System.Text.RegularExpressions.GeneratedRegex(@"^[1]+[3-9]+\d{9}$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex();
    }
}

六、实例5:验证身份证号码的格式

// 用正则表达式验证身份证号码合法性
namespace _074
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Button? button1;
        private TextBox? textBox1;
        private Label? label1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(16, 28),
                Name = "label1",
                Size = new Size(104, 17),
                TabIndex = 0,
                Text = "输入身份证号码:"
            };
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(125, 22),
                Name = "textBox1",
                Size = new Size(140, 23),
                TabIndex = 1
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(190, 57),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 2,
                Text = "验证",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(280, 99),
                TabIndex = 0,
                TabStop = false,
                Text = "验证身份证号码"
            };
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();

            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(304, 123);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "验证身份证号码合法性";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }

        private void Button1_Click(object? sender, EventArgs e)
        {
            if (!IsIDcard(textBox1!.Text.Trim()))
            { 
                MessageBox.Show("身份证号不正确!!!");
            }
            else 
            { 
                MessageBox.Show("身份证号正确!!!!!"); 
            }
        }
        /// <summary>
        /// 验证身份证号是否正确
        /// </summary>
        /// <param name="idcard">身份证号字符串</param>
        /// <returns>返回布尔值</returns>
        public static bool IsIDcard(string idcard)
        {
            if (DateTime.IsLeapYear(Convert.ToInt32(idcard.Substring(6, 4))))
            {
                return MyRegex().IsMatch(idcard);
            }
            else
            {
                return MyRegex1().IsMatch(idcard);
            }    
        }

        [System.Text.RegularExpressions.GeneratedRegex(@"(^[1-9]\d{5}(19|20)\d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2]\d|3[0-1])|(04|06|09|11)(0[1-9]|[1-2]\d|30)|02(0[1-9]|[1-2]\d))\d{3}[\dXx]$)")]
        private static partial System.Text.RegularExpressions.Regex MyRegex();

        [System.Text.RegularExpressions.GeneratedRegex(@"(^[1-9]\d{5}(19|20)\d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2]\d|3[0-1])|(04|06|09|11)(0[1-9]|[1-2]\d|30)|02(0[1-9]|1\d|2[0-8]))\d{3}[\dXx]$)")]
        private static partial System.Text.RegularExpressions.Regex MyRegex1();
    }
}

七、实例6:验证小数点后位数是否2位

// 验证小数点后是否为2位
namespace _075
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Button? button1;
        private TextBox? textBox1;
        private Label? label1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(25, 30),
                Name = "label1",
                Size = new Size(68, 17),
                TabIndex = 0,
                Text = "输入小数:"
            };
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(121, 24),
                Name = "textBox1",
                Size = new Size(135, 23),
                TabIndex = 1
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(181, 59),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 2,
                Text = "验证",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 11),
                Name = "groupBox1",
                Size = new Size(280, 100),
                TabIndex = 0,
                TabStop = false,
                Text = "验证小数点后位数"
            };
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();

            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(304, 123);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "验证小数点后是否2位";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }

        private void Button1_Click(object? sender, EventArgs e)
        {
            if (!IsDecimal(textBox1!.Text.Trim()))
            { 
                MessageBox.Show("请输入两位小数!!!", "提示"); 
            }
            else
            { 
                MessageBox.Show("输入正确!!!!!", "提示"); 
            }
        }
        /// <summary>
        /// 验证小数是否正确
        /// 等效的正则:@"^[0-9]+\.\d{2}$"
        /// 等效的正则:@"^[0-9]+(.\d{2})$"
        /// 等效的正则:@"^[0-9]+.\d{2}$"
        /// 等效的正则:@"^[0-9]+\.[0-9]{2}$"
        /// </summary>
        /// <param name="str_decimal">小数字符串</param>
        /// <returns>返回布尔值</returns>
        public static bool IsDecimal(string str_decimal)
        {
            return MyRegex().IsMatch(str_decimal);
        }

        [System.Text.RegularExpressions.GeneratedRegex(@"^[0-9]+(.\d{2})?$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex();
    }
}

八、实例7:验证输入的数值是否有效月

// 用正则表达式验证输入的数字是否有效月
namespace _076
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Button? button1;
        private TextBox? textBox1;
        private Label? label1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(34, 33),
                Name = "label1",
                Size = new Size(92, 17),
                TabIndex = 0,
                Text = "输入月份数值:"
            };
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(132, 30),
                Name = "textBox1",
                Size = new Size(100, 23),
                TabIndex = 1
            };
            // 
            // button1
            // 

            button1 = new Button
            {
                Location = new Point(157, 59),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 2,
                Text = "验证",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 11),
                Name = "groupBox1",
                Size = new Size(280, 100),
                TabIndex = 0,
                TabStop = false,
                Text = "验证是否有效的月"
            };
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();

            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(304, 123);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "验证数字是否有效月";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }

        private void Button1_Click(object? sender, EventArgs e)
        {
            if (!IsMonth(textBox1!.Text.Trim()))
            {
                MessageBox.Show("输入月份不正确!!!", "提示");
            }
            else
            {
                MessageBox.Show("输入信息正确!!!!!", "提示"); 
            }
        }
        /// <summary>
        /// 验证月份是否正确
        /// </summary>
        /// <param name="str_Month">月份信息字符串</param>
        /// <returns>返回布尔值</returns>
        public static bool IsMonth(string str_Month)
        {
            return MyRegex().IsMatch(str_Month);
        }

        [System.Text.RegularExpressions.GeneratedRegex(@"^(0?[[1-9]|1[0-2])$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex();
    }
}

 

九、实例8:用两种方法分别验证输入是否有效日期

//DateTime.ParseExact方法验证输入的日期格式是否正确
//用正则表达式验证输入的日期格式是否正确
using System.Globalization;

namespace _077
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Button? button1;
        private Button? button2;
        private static TextBox? textBox1;
        private Label? label1;
        private Label?label2;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(31, 21),
                Name = "label1",
                Size = new Size(92, 17),
                TabIndex = 0,
                Text = "输入日期数值:"
            };
            // 
            // label2
            // 
            label2 = new Label
            {
                AutoSize = true,
                Location = new Point(31, 38),
                Name = "label2",
                Size = new Size(96, 17),
                TabIndex = 3,
                Text = "(如:20240528)"
            };
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(147, 15),
                Name = "textBox1",
                Size = new Size(100, 23),
                TabIndex = 1
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(172, 46),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 2,
                Text = "验证1",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // button2
            // 
            button2 = new Button
            {
                Location = new Point(172, 69),
                Name = "button2",
                Size = new Size(75, 23),
                TabIndex = 4,
                Text = "验证2",
                UseVisualStyleBackColor = true
            };
            button2.Click += Button2_Click;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 11),
                Name = "groupBox1",
                Size = new Size(280, 100),
                TabIndex = 0,
                TabStop = false,
                Text = "是否有效日期"
            };
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(button2);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label1);
            groupBox1.Controls.Add(label2);
            groupBox1.SuspendLayout();
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(304, 123);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "验证数值是否有效日期";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }
        /// <summary>
        /// DateTime.ParseExact方法验证输入的日期格式是否正确
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            string format = "yyyyMMdd";
            CultureInfo provider = CultureInfo.CurrentCulture;
            try
            {
                DateTime result = DateTime.ParseExact(textBox1!.Text.Trim(), format, provider);
                MessageBox.Show("输入的日期格式正确.");
            }
            catch (FormatException)
            {
                MessageBox.Show("输入的日期格式不对.");
            }
        }
        /// <summary>
        /// 用正则表达式验证输入的日期格式是否正确
        /// </summary>
        private void Button2_Click(object? sender, EventArgs e)
        {
            int year = Convert.ToInt32(textBox1!.Text.Substring(0, 4));
            int month = Convert.ToInt32(textBox1!.Text.Substring(4, 2));
            string date = textBox1!.Text.Substring(6, 2);

            if (textBox1!.Text != "")
            {
                if (year <= 9999 && year >= 1800)
                {
                    if(month > 1 || month <= 12)
                    {
                        if (IsDay(year,month,date))
                        {
                            MessageBox.Show("输入天数正确!!!", "提示");
                        }
                        else
                        {
                            MessageBox.Show("输入天数不正确!!!!!", "提示");
                        }
                    }
                    else
                    {
                        MessageBox.Show("输入的月不正确!!!", "提示");
                    }
                }
                else
                {
                    MessageBox.Show("输入的年不正确!!!", "提示");
                }
            }
            else
            {
                MessageBox.Show("输入的日期不能为空!", "提示");
            }  
        }

        /// < summary >
        /// 验证输入的数值是否是有效的日期
        /// 验证顺序:是小月?是大月?是2月?都不是那就是其它了
        /// </ summary >
        /// < param name = "daytime" > 每月的天数 </ param >
        /// < returns > 返回布尔值 </ returns >
        private static bool IsDay(int year, int month, string daytime)
        {
            if (month == 04 || month == 06 || month == 09 || month == 11 || month == 4 || month == 6 || month == 9)
            {
                return MyRegex().IsMatch(daytime); 
            }
            else if (month == 01 || month == 03 || month == 05 || month == 07 || month == 08 || month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
             {
                return MyRegex1().IsMatch(daytime);
             }
            else if (month == 2)
             {
                 if (DateTime.IsLeapYear(year))
                 {
                     return MyRegex2().IsMatch(daytime);
                 }
                 else
                 {
                     return MyRegex3().IsMatch(daytime);
                 }
             }
             else
             {
                 return false;
             }
        }

        [System.Text.RegularExpressions.GeneratedRegex(@"^((0?[1-9])|((1|2)[0-9])|30)$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex();
        [System.Text.RegularExpressions.GeneratedRegex(@"^((0?[1-9])|((1|2)[0-9])|30|31)$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex1();
        [System.Text.RegularExpressions.GeneratedRegex(@"^((0?[1-9])|((1|2)[0-9]))$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex2();
        [System.Text.RegularExpressions.GeneratedRegex(@"^((0?[1-9])|((1|2)[0-8]))$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex3();
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1422088.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

springBoot+Vue汽车销售源码

源码描述: 汽车销售管理系统源码基于spring boot以及Vue开发。 针对汽车销售提供客户信息、车辆信息、订单信息、销售人员管理、 财务报表等功能&#xff0c;提供经理和销售两种角色进行管理。 技术架构&#xff1a; idea(推荐)、jdk1.8、mysql5.X(不能为8驱动不匹配)、ma…

exec函数族和守护进程

exec函数族 进程调用exec函数族执行某个程序 进程当前内容被指定程序替换 实现让父子进程实现不同的程序: 父进程创建子进程 子进程调用exec函数族 父进程不受影响 execl和execlp #include <stdio.h> int execl (const char * path, const char * arg , ...); i…

计算机网络_1.2因特网概述

1.2因特网概述 一、网络、互联网与因特网的区别与联系1、网络2、互联网3、因特网4、 互联网与因特网辨析 二、因特网介绍1、因特网发展的三个阶段2、因特网简介&#xff08;1&#xff09;因特网服务提供者&#xff08;ISP&#xff09;&#xff08;2&#xff09;因特网已经发展成…

中科星图——2020年全球30米地表覆盖精细分类产品V1.0(29个地表覆盖类型)

数据名称&#xff1a; 2020年全球30米地表覆盖精细分类产品V1.0 GLC_FCS30 长时序 地表覆盖 动态监测 全球 数据来源&#xff1a; 中国科学院空天信息创新研究院 时空范围&#xff1a; 2015-2020年 空间范围&#xff1a; 全球 数据简介&#xff1a; 地表覆盖分布…

redisTemplate.opsForValue()

redisTemplate ​在Spring Data Redis中&#xff0c;redisTemplate 是一个非常重要的组件&#xff0c;它为开发者提供了各种操作 Redis 的方法。对于 opsForValue() 方法&#xff0c;它是用来获取一个操作字符串值的操作对象。这意味着你可以使用它来执行各种字符串相关的操作…

海外短剧系统国际短剧源码h5多语言版app挂载tiktok油管ins

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目 前言 一、海外短剧系统是什么&#xff1f; 二、海外短剧系统功能与运营方式介绍 1.系统功能 2.短剧APP运营方式 总结 前言 本文简单介绍海外短剧系统的功能&#xff…

MySQL数据库如何生成分组排序的序号

点击上方蓝字关注我 经常进行数据分析的小伙伴经常会需要生成序号或进行数据分组排序并生成序号。在MySQL8.0中可以使用窗口函数来实现&#xff0c;可以参考历史文章有了这些函数&#xff0c;统计分析事半功倍进行了解。而MySQL5.7中由于没有这类函数&#xff0c;该如何实现呢&…

安全测试-pikachu靶场搭建

pikachu靶场搭建 文章目录 pikachu安装步骤 pikachu pikachu是一个自带web漏洞的应用系统&#xff0c;在这里包含了常见的web安全漏洞&#xff0c;也就是练习的靶场。 练习内容包括&#xff1a; 1.暴力破解 2.XSS 3.CSRF 4.SQL注入 5.RCE 6.文件包含 7.不安全的文件下载 8.不安…

【智能家居入门2】(MQTT协议、微信小程序、STM32、ONENET云平台)

此篇智能家居入门与前两篇类似&#xff0c;但是是使用MQTT协议接入ONENET云平台&#xff0c;实现微信小程序与下位机的通信&#xff0c;这里相较于使用http协议的那两篇博客&#xff0c;在主程序中添加了独立看门狗防止程序卡死和服务器掉线问题。后续还有使用MQTT协议连接MQTT…

Android悬浮窗实现步骤

最近想做一个悬浮窗秒表的功能&#xff0c;所以看下悬浮窗具体的实现步骤 1、初识WindowManager 实现悬浮窗主要用到的是WindowManager SystemService(Context.WINDOW_SERVICE) public interface WindowManager extends ViewManager {... }WindowManager是接口类&#xff0c…

Observability:在 Elastic Stack 8.12 中使用 Elastic Agent 性能预设

作者&#xff1a;来自 Elastic Nima Rezainia, Bill Easton 8.12 中 Elastic Agent 性能有了重大改进 最新版本 8.12 标志着 Elastic Agent 和 Beats 调整方面的重大转变。 在此更新中&#xff0c;Elastic 引入了 Performance Presets&#xff0c;旨在简化用户的调整过程并增强…

计算机网络_1.3电路交换、分组交换和报文交换

1.3电路交换、分组交换和报文交换 一、电路交换1、“电路交换”例子引入2、电路交换的三个阶段3、计算机之间的数据传送不适合采用电路交换 二、分组交换1、发送方&#xff08;1&#xff09;报文&#xff08;2&#xff09;分组&#xff08;3&#xff09;首部 2、交换节点3、接收…

机器学习模型预测贷款审批

机器学习模型预测贷款审批 作者&#xff1a;i阿极 作者简介&#xff1a;数据分析领域优质创作者、多项比赛获奖者&#xff1a;博主个人首页 &#x1f60a;&#x1f60a;&#x1f60a;如果觉得文章不错或能帮助到你学习&#xff0c;可以点赞&#x1f44d;收藏&#x1f4c1;评论&…

CHS_05.2.3.4_1+信号量机制

CHS_05.2.3.4_1信号量机制 知识总览信号量机制信号量机制——整型信号量信号量机制——记录型信号量知识回顾 在这个小节中 我们会学习信号量 机制这个极其重要的知识点 知识总览 在考研当中 我们需要掌握两种类型的信号量 一种是整形信号量 另一种是记录型信号量 我们会在后面…

AsyncLocal是如何实现在Thread直接传值的?

一&#xff1a;背景 1. 讲故事 这个问题的由来是在.NET高级调试训练营第十期分享ThreadStatic底层玩法的时候&#xff0c;有朋友提出了AsyncLocal是如何实现的&#xff0c;虽然做了口头上的表述&#xff0c;但总还是会不具体&#xff0c;所以觉得有必要用文字图表的方式来系统…

Camunda简介

&#x1f496;专栏简介 ✔️本专栏将从Camunda(卡蒙达) 7中的关键概念到实现中国式工作流相关功能。 ✔️文章中只包含演示核心代码及测试数据&#xff0c;完整代码可查看作者的开源项目snail-camunda ✔️请给snail-camunda 点颗星吧&#x1f618; &#x1f496;系列文章 …

【PyTorch实战演练】Fast R-CNN中的RoI(Region of Interest)池化详解

文章目录 0. 前言1. ROI池化的提出背景2. RoI池化的结构与工作原理3. RoI池化的作用及意义4. RoI使用示例 0. 前言 按照国际惯例&#xff0c;首先声明&#xff1a;本文只是我自己学习的理解&#xff0c;虽然参考了他人的宝贵见解及成果&#xff0c;但是内容可能存在不准确的地方…

Linux第40步_移植ST公司uboot的第1步_创建配置文件_设备树_修改电源管理和sdmmc节点

ST公司uboot移植分两步走&#xff1a; 第1步&#xff1a;完成“创建配置文件&#xff0c;设备树&#xff0c;修改电源管理和sdmmc节点&#xff0c;以及shell脚本和编译”。 第2步“完成”修改网络驱动、USB OTG设备树和LCD驱动&#xff0c;以及编译和烧写测试“。 移植太复杂…

Spring 中获取 Bean 对象的三种方式

目录 1、根据名称获取Bean 2、根据Bean类型获取Bean 3、根据 Bean 名称 Bean 类型来获取 Bean&#xff08;好的解决方法&#xff09; 假设 Bean 对象是 User&#xff0c;并存储到 Spring 中&#xff0c;注册到 xml 文件中 public class User {public String sayHi(){retur…

小型洗衣机什么牌子好又便宜?家用内衣洗衣机推荐

近几年家用洗衣机标准容积的大大增加&#xff0c;从5Kg、6Kg升级到9Kg、10Kg。大容量洗衣机满足了家庭中清洗大件衣物、床上用品的需求。但由于普通大型洗衣机所洗衣物混杂&#xff0c;很多时候内衣袜子、宝宝衣物数量不多&#xff0c;却也并不适合放在一起扔进大型洗衣机中清洗…