Hi Everyone,

I have one text box named txtYear.text and this text box will accept only Year Value i.e. 2011, 2012 and so on. Now i want to put a validation on the text box like, if user enters the value like 1,03,54 in text box then the system should show an error message to user saying that, the value is not year or something. The text box should accept only if the user enters valid year value like 2010, 1907 and so on.

I am working on VB.NET 2010 and the language is VB.

I have seek the help from google but failed to get the proper solution. CAN ANYONE HELP ME?

Try a function like this:

Private Function CheckIfYear(byval sYear As String) As Boolean
        Dim dt As New DateTime(Cint(sYear),1,1,1,1,1)
        Return True
    Catch ex As Exception
        Return False
    End Try
End Function

Then use it in the TextBox's Leave event:

Private Sub TextBox_Leave(sender As System.Object, e As System.EventArgs) Handles TextBox1.Leave
    If TextBox1.Text.Length = 4 Then
        If CheckIfYear(TextBox1.Text) = False Then
           MsgBox("You have entered an incorrect year")
        End If
        MsgBox("Please enter a four digit date.")
    End If
End Sub

Might I recommond a read-through of: User Input Validation in Windows Forms. Also, Google "winforms validation"; you'll find some decent tutorials.

There are a few issues I have with Begginnerdev's suggestion:

  1. Not focusing on the textbox, bypasses the validation (eg. click an OK button before clicking the textbox). There are work-arounds, but aren't very scaleable.
  2. The user gets trapped until they enter a valid value. This is mostly personal preference, and not always a big issue.
  3. Message boxes for every invalid value can be a pain to the user. Again, personal preference, but a consideration.

I could go on, and have been in a few debates over this, but I want to point out that it isn't necessarily bad design. It comes down to personal preference in some sense, but I prefer other solutions that are more scalable and I think the user will be happier with.

commented: True, but this was only for proof of concept. = ) +7

you can use masked textbox, there you can customized the user input, then set MaxLength to '4' in the properties window. and if you need to limit the years you can use
If year < 2000 And year > 2050 then ... something like that