ADM
ADM

Reputation: 1610

VB6: validating date with a certain format

I have built a form using Visual Basic 6. Everything goes great, the form inserts the data in my database and no problems here at all.

Now I need to validate the date field, I need the dates entered to have this format: dd/mm/yyyy

I'm doing:

Private Sub txtMyText_Validate(Index As Integer, Cancel As Boolean)
If IsDate(Format$(txtMyText(9).Text, "dd/mm/yyyy")) Or txtMyText(9).Text = "" Then
txtMyText(9).SetFocus
Else
txtMyText(9).SetFocus
MsgBox "Please enter a valid date with this format: dd/mm/yyyy."
End If
End Sub

But this code is not working. When I enter a date with this format dd/mm/yy the flow follows to the inserting function and I get an error there cause it is not a dd/mm/yyyy.

Can you please help me to fix this code?

Thanks a lot!

Upvotes: 2

Views: 14107

Answers (1)

ADM
ADM

Reputation: 1610

Use this in your insert into database line for the date field:

Format(txtMyText(9).Text, "dd/mm/yyyy") 

That will solve dates entered as dd/mm/yy or yyyy/mm/dd

And to prevent from entering integers or strings instead of dates:

Private Sub txtMyText_Validate(Index As Integer, Cancel As Boolean)
    If Not IsDate(txtMyText(9).Text) Then
    MsgBox "Enter a valid date with this format: dd/mm/yyyy"
    Cancel = True
    End If
End Sub

Upvotes: 1

Related Questions