I've had a request from my client to "improve" the User Experience of typing dates into the DatePicker with a variety of different delimiters. Their user story is:
This has come in as a late requirement, the forms are built and there's several datepickers working well so I was hoping there was some code that can be used on a datepicker property that would replace any separating characters with a slash so that I don't have to reformat all my date data.
The reason typing is needed is that the dates that need to be entered can sometimes be many years in the past which would take a number of clicks to input with the calendar part of the datepicker.
Luckily the dates will always be entered in UK format "dd/mm/yyyy".
The client has said that we need to accommodate the following date separators (./-):
I've had some conversations about this with the client as it's a real edge case but they are adamant that they would like to have this working.
In the Format and DefaultDate property:
Text(
Substitute(dteDeferredStart.SelectedDate,"-","/"),
"dd/mm/yyyy"
)
In the DefaultDate property
Text(
Substitute(Parent.Default,"-","/"),
"dd/mm/yyyy"
)
With either of these bits of code in the property if I type 17-05-2023 into the datepicker the output SelectedDate is Blank.
Starting to tear my hair out now.
There's a whole lot of validation code linked up with these dates so it's going to be a big rewrite if I have to change anything outside of the datepicker.
Hoping you wonderful people will be able to enlighten me.
I think this is a good use case for Regular Expressions in Power Apps. I recommend you read documentation from Microsoft first.
In your specific case you should use the Match()
function in a TextInput control's OnChange property and UpdateContext() to save the parsed date in a local variable. You can then use the local variable in the Default property of the DatePicker and Reset() to reflect the inputting of dates in the TextInput control. You should also set DelayOutput to true for the TextInput so that the logic doesn't run for every keystroke.
The RegEx pattern should look something like this:
(\d{1,2}).(\d{1,2}).(\d{4})
This will return a table of 3 rows (day,month,year). The benefit is that the user can use any of the separators. Use combinations of First()
, Last()
, FirstN()
and LastN()
inside a Date()
function to get a Date type.
Here's what I tested with in the TextInput.OnChange:
With({ matches: First(MatchAll(Self.Text,"(\d{1,2}).(\d{1,2}).(\d{4})",MatchOptions.Contains)).SubMatches },
Set(myDate,Date(
Value(Last(matches).Value),
Value(Last(FirstN(matches,2)).Value),
Value(First(matches).Value)
))
);