user1795999
user1795999

Reputation: 301

Validate the date format

I have a textbox in my form in vb 2010 which should accept only dates and only in the format of "yyyy/mm/dd"

How to achieve this? Please help

Upvotes: 0

Views: 10501

Answers (3)

Pierre-Olivier Pignon
Pierre-Olivier Pignon

Reputation: 747

You can try this:

DateTime.TryParseExact(dateToTest, "yyyy/MM/dd", New CultureInfo("us-US"), DateTimeStyles.None, result) 

Upvotes: 0

spajce
spajce

Reputation: 7082

Private Sub TextBox2_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox2.Validating
    Dim test As Date
    If Date.TryParseExact(TextBox2.Text.ToString(), "yyyy/mm/dd", _
                          System.Globalization.CultureInfo.CurrentCulture, _
                          Globalization.DateTimeStyles.None, test) Then
        MessageBox.Show("Ok")
        'TODO: ok
    Else
        e.Cancel = True
        'TODO: not ok
    End If
End Sub

Upvotes: 1

DevelopmentIsMyPassion
DevelopmentIsMyPassion

Reputation: 3591

If you use datepicker control then you can set to custom format as you like. In the form load event use below

DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "yyyy/mm/dd"

Let me know if it helps.

Upvotes: 0

Related Questions