我正在尝试专门为我的应用程序创建一个自定义控件,该控件将使用 maskedTextBox 来限制输入的输入数据。
现在我想用 C# 实现这个。
class CustomDateMask:System.Windows.Forms.MaskedTextBox
this.Mask = "00/00/2\000"; // For year 2000 and above, date format is "dd/mm/yyyy"
this.ValidatingType = typeof(System.DateTime);
我看到了一个正则表达式,通过捕获输入离开和按键事件来限制日期来验证我的日期。
现在我的正则表达式是这样的
string regYear =@"(200[8,9]|201[0-9])"; //for year from 2008-2019 Plz correct this RegEx if wrong.
string regMonth =@"(0[1-9]|1[012])";
string regDate =@"(0[1-9]|[12][0-9]|3[01])";
string seperator=@"[- /]";
string ddmmyyyy=regDate+seperator+regMonth+seperator+regYear;
我看到了 link 关于检查日期格式的正则表达式。 现在我想在 C# 中使用我在上面链接中提供的这段代码。该代码是用 Perl 编写的,我想在 C# 中执行相同的功能。但我不知道如何从下面给出的正则表达式中检索日期、月份、年份,例如:从 1 美元、2 美元、3 美元起。
sub isvaliddate {
my $input = shift;
if ($input =~ m!^((?:19|20)\d\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$!) {
# At this point, $1 holds the year, $2 the month and $3 the day of the date entered
if ($3 == 31 and ($2 == 4 or $2 == 6 or $2 == 9 or $2 == 11)) {
return 0; # 31st of a month with 30 days
} elsif ($3 >= 30 and $2 == 2) {
return 0; # February 30th or 31st
} elsif ($2 == 2 and $3 == 29 and not ($1 % 4 == 0 and ($1 % 100 != 0 or $1 % 400 == 0))) {
return 0; # February 29th outside a leap year
} else {
return 1; # Valid date
}
} else {
return 0; # Not a date
}
}
我想使用 this.DateOnly、this.MonthOnly、this.YearOnly 返回用户日期部分、月份部分和年份部分,我需要提取这些值。
我主要关心的问题
保存从 maskedTextBox
的三个变量中输入的日期的年、月和日
最佳答案
Perl 的 $1
、$2
和 $3
相当于 C# 的 m.Groups[1].Value
、m.Groups[2].Value
等。
要在示例中提取它们,您可以使用
Match m = Regex.Match(ddmmyyyy);
if (m.Success) {
string day = m.Groups[1];
string month = m.Groups[2];
string year = m.Groups[3];
}
关于c# - 使用 MaskedTextBox 实现日期时间选择器功能。使用 RegEx 完成验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2186670/