Sometime you can’t found the solution to a basic problem.
How can I use DesktopTextField to let let user input a currency value in his locale format. I lost myself with validation mask, DesktopTextField.Format, DesktopTextField.Textchanged…
My question is not about Currency type but about DesktopTextField control. How to configure it to help user type a currency value in is locale
Ex: “$1,200.00” or “1 200,00€”
How to allow only numerics, max two decimal digits and a currency sign according to user locale ?
My approach: no currency symbols in the field, just numbers and decimal and thousands separators. With the help of the “KeyDown” event, all other inputs are filtered out directly when typing. I have a method called FilterKeys, which checks if the pressed key is allowed and then returns “False” (Key is allowed) else “True” (Key is ignored). Have a look at the documentation for DesktopTextField.KeyDown Event. Keys are filtered with
If Keyboard.AsyncKeyDown(&h1D) Then Return False // number 0
Finally, at the “FocusLost” Event, formatting the content with Format().
somehow i would give the user the freedom of input and
show the input value as real value.
the input mask in xojo i not like.
Sub TextChanged() Handles TextChanged
Var v As Currency = 0
#Pragma BreakOnExceptions False
Try
v = Currency.FromString(Me.Text,Locale.Current)
v = Round(v*100)/100.0
Catch e As RuntimeException
End Try
Label1.Text = v.ToString(Locale.Current)
System.DebugLog v.ToString()
End Sub
maybe create a container control for this value input to switch between input and display.
This the solution I choose. Thanks @MarkusR and other members for their help. Fell free to comment or adjust my code.
For my DesktopTextField I had this event handlers
Sub FocusLost()
Var c As Currency = 0
// Try to convert as a Locale Currency
#Pragma BreakOnExceptions False
Try
c = Currency.FromString(Me.Text,Locale.Current)
Catch e As RuntimeException
End Try
Me.Text = c.ToString(Locale.Current)
End Sub
And for key down management
Function KeyDown(key As String) As Boolean
Var re As New RegEx
Var match As RegExMatch
re.SearchPattern = "[a-z]"
match = re.Search(key)
If match = Nil Then Return False Else Return True
End Function
I like the regex idea, but I would suggest that you list the things to allow instead of those that you don’t. You’ll need to create a dynamic constant for currency symbols and whether the language allows spaces probably but then the pattern could be:
Thank you @Greg_O but with my approach RegEx is more complex because I want keydown return false if user press an alphanumeric key. I want to allow ESC, TAB, ENTER keys…
My search pattern contains characters I don’t want not authorised characters