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.
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.
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!