Validate Date with Regex Issue

I have a GUI script I created using WPF and i’m having trouble trying to validate the date that’s in a text box field. Here is my variables and conditional statement and the $Date.text runs in the console as 02-07-2020.
<p style=“padding-left: 40px;”>$InputDate = $Date.text</p>
<p style=“padding-left: 40px;”>[regex]$DateRegex = ‘[1][0-2]-(0[1-3]|1[0-9]|2[0-9]|3[01])-202[0-9]$’</p>
<p style=“padding-left: 40px;”>If ($InputDate -match $DateRegex) = False</p>
This returns false even though the date is formatted correctly. If I run the following, it returns “True” like I’m expecting it to.
<p style=“padding-left: 40px;”>$InputDate = ‘02-07-2020’</p>
<p style=“padding-left: 40px;”>[regex]$DateRegex = ‘[2][0-2]-(0[1-3]|1[0-9]|2[0-9]|3[01])-202[0-9]$’</p>
<p style=“padding-left: 40px;”>If ($InputDate -match $DateRegex) = True</p>
Is there a better way to validate a date from a textbox field, or is there something I’m missing to get this to work correctly? Even if I do $InputDate = Get-date -format MM-dd-yyyy, this still comes out to false. Any help would be greatly appreciated.

 


  1. 0-1 ↩︎

  2. 0-1 ↩︎

How about this: https://stackoverflow.com/questions/14525236/powershell-regex-for-mm-dd-yyyy

$Dateregex = "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}"
$InputDate -match $DateRegex

[pre]$haha=get-date ‘02-07-200’
if($haha){
$time=New-TimeSpan -start $haha -end (get-date)
if($time -lt 5000 -or $time -gt -5000){$true}else{break}
}else{break}[/pre]

This works: https://stackoverflow.com/questions/15491894/regex-to-validate-date-format-dd-mm-yyyy

I tested with these 3 dates

$InputDate = '02-07-2020'
$InputDate = '07-31-2020'
$InputDate = '06-27-2023'
$Dateregex = "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}"
$InputDate -match $DateRegex

I don’t know if this is causing your problem, but you’re “doubling-up” on regular expressions. The -Match operator takes a string, you don’t need to create a [regex] object.

$InputDate = $Date.text

$DateRegex = '^[0-1][0-2]-(0[1-3]|1[0-9]|2[0-9]|3[01])-202[0-9]$'

$InputDate -match $DateRegex

Or, you can create a [regex] and use its match() method.

$InputDate = ‘02-07-2020’

[regex]$DateRegex = ‘[1][0-2]-(0[1-3]|1[0-9]|2[0-9]|3[01])-202[0-9]$’

$DateRegex.Match($InputDate)

 


  1. 0-1 ↩︎

Thanks for the replies, the problem I had was with my regular expression code. I corrected with the code you provided and it worked as expected. Thanks!