正则表达式在程序设计中有着重要的位置,经常被用于处理字符串信息。
用Regex类的IsMatch方法,使用正则表达式可以验证电话号码是否合法。
一、涉及到的知识点
Regex类的IsMatch方法用于指示正则表达式使用pattern参数中指定的正则表达式是否在输入字符串中找到匹配项。语法格式如下:
cs
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
身份证号正则表达式:
cs
//闰年
^[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:验证电话号码的格式
cs
//使用正则表达式验证电话号码
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:验证密码的格式
cs
// 使用正则表达式验证密码格式
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:验证邮编的格式
cs
// 用正则表达式验证邮编合法性
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:验证手机号码的格式
cs
//用正则表达式验证手机号码合法性
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:验证身份证号码的格式
cs
// 用正则表达式验证身份证号码合法性
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位
cs
// 验证小数点后是否为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:验证输入的数值是否有效月
cs
// 用正则表达式验证输入的数字是否有效月
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:用两种方法分别验证输入是否有效日期
cs
//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();
}
}