B4J Question textfield string format

medifor

Member
Licensed User
how do I check that a string in a specific format is entered in a textfield? in my case in the format "dd-mm-yyyy"
 

behnam_tr

Active Member
Licensed User
Longtime User
dd/mm/yyyy >> 01/01/2020
B4X:
Sub validate_date(tx As String) As Boolean
    Dim pt As String ="[0-9]{2}/[0-9]{2}/[0-9]{4}"
  
  If Regex.IsMatch(pt,tx) Then return true
 
  Return False
End Sub

using :
B4X:
if validate_date(textfield1.text)=true then
   'your code here
else
   'your code here
endif
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Another option:
B4X:
Private Sub TextField1_TextChanged (Old As String, New As String)
    Dim IsValid As Boolean = True
    Try
        If New <> "" Then
            Dim t As Long = DateTime.DateParse(New)
            Dim year As Int = DateTime.GetYear(t)
            If year < 1900 Or year > 2100 Then IsValid = False
        End If
    Catch
        IsValid = False
    End Try
    If IsValid Then
        TextField1.SetColorAndBorder(xui.Color_White, 1dip, xui.Color_LightGray, 2dip)
    Else
        TextField1.SetColorAndBorder(xui.Color_White, 1dip, xui.Color_Red, 2dip)
    End If
End Sub

This is a good option when you want to make sure that you can parse the date. In some cases, invalid strings can still be parsed. Depending on your usage it might be problematic (you can always take the ticks value and convert it to string with DateTime.Date).
 
Upvote 0

medifor

Member
Licensed User
dd/mm/yyyy >> 01/01/2020
B4X:
Sub validate_date(tx As String) As Boolean
    Dim pt As String ="[0-9]{2}/[0-9]{2}/[0-9]{4}"
 
  If Regex.IsMatch(pt,tx) Then return true

  Return False
End Sub

using :
B4X:
if validate_date(textfield1.text)=true then
   'your code here
else
   'your code here
endif
is ok , tkanks
 
Upvote 0

medifor

Member
Licensed User
Another option:
B4X:
Private Sub TextField1_TextChanged (Old As String, New As String)
    Dim IsValid As Boolean = True
    Try
        If New <> "" Then
            Dim t As Long = DateTime.DateParse(New)
            Dim year As Int = DateTime.GetYear(t)
            If year < 1900 Or year > 2100 Then IsValid = False
        End If
    Catch
        IsValid = False
    End Try
    If IsValid Then
        TextField1.SetColorAndBorder(xui.Color_White, 1dip, xui.Color_LightGray, 2dip)
    Else
        TextField1.SetColorAndBorder(xui.Color_White, 1dip, xui.Color_Red, 2dip)
    End If
End Sub

This is a good option when you want to make sure that you can parse the date. In some cases, invalid strings can still be parsed. Depending on your usage it might be problematic (you can always take the ticks value and convert it to string with DateTime.Date).

SetColorAndBorder : unknown member
 
Upvote 0
Top