开发者

Implement Date Time Picker functionality with MaskedTextBox. Validation done with RegEx

开发者 https://www.devze.com 2022-12-19 12:00 出处:网络
I am trying to create a Custom control specifically for my application which would be using maskedTextBox to restrict input data entered.

I am trying to create a Custom control specifically for my application which would be using maskedTextBox to restrict input data entered.

Now i want to implement this in 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);

I saw a regular expression for the same to validate my date by restricting date by capturing enter leave and keypress events.

Now my RegExp comes out to be like this

    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;

I saw a link regarding the Regular expression for checking Date Format. No开发者_Go百科w I want to use this code in C# that i provided you in above link. This code is written in Perl and I want to do the same functionality in C#. But I dont know how to Retrieve Date, Month, Year from this Regular Expression as extracted in below given eg. from $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
  }
}

I want to return user date part, month part and year part using this.DateOnly, this.MonthOnly, this.YearOnly for which i need to extract these values.

My Major Concern

hold year, month and day of the date entered in three variables from maskedTextBox


Perl's $1, $2, and $3 are equivalent to C#'s m.Groups[1].Value, m.Groups[2].Value, and so on.

To extract them in your example, you'd use

Match m = Regex.Match(ddmmyyyy);
if (m.Success) {
    string day = m.Groups[1];
    string month = m.Groups[2];
    string year = m.Groups[3];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消