Entered DateTime error handling

If user enters a non-valid date in a textfield i.e. 2023-12-32, what is a simple way to handle this?

Code could be in the TextField FocusLost event:
BodyLogDate = DateTime.FromString(DateLog_field.Text)
(BodyLogDate is a DateTime Property)

You’ll get an Exception. If you wrap your code in a try-catch block, you’ll know if the parsing failed.

I get a RuntimeException. I have tried a few versions of this:
Try
BodyLogDate = DateTime.FromString(DateLog_field.Text)
Catch e As RuntimeException
Return
End Try


Var d As DateTime

Try 
  d = DateTime.FromString("2023-12-32")
Catch
  d = Nil
End

If d = Nil Then MessageBox "Invalid date"

break

Thanks, but it’s the same problem. It doesn’t return Nil but a runtimeException.

You are debugging with break on Exceptions, that is expected. You need to Resume your debug to see the Catch in action.


First you get RuntimeException
image

Then you get InvalidArgumentException
image

Then you see the MessageBox
image

I’m not saying to you replace whatever you are using by this example, just showing a way to handle it.

If after conversion you get a Nil, the date is invalid, manage it as you wish.

Got it. Thanks both…

I think this is the solution:

Try
  BodyLogDate= DateTime.FromString(DateLog_field.Text)
Catch e As InvalidArgumentException
  MsgBox ("Please enter proper date format!"+chr(13)+_
  "yyyy-mm-dd")
  me.SetFocus
  Return
End Try

see also #Pragma BreakOnExceptions False
it would not always interupt your app at testing from ide.
https://documentation.xojo.com/api/language/pragma_directives.html#pragma-directives