TM80 TM80 - 2 years ago 101 Question

Checking that TextBox.Text.Length is between 1 and 10

I am trying to validate the number of characters placed inside a

but am having some trouble. The code I'm using is as follows:

If Not ((TextBox5.Text.Length) <= 1) Or ((TextBox5.Text.Length) >= 10) Then
MsgBox("Invalid date entry. Use the the following format: DD-MM-YYYY.")
'do whatever
End If

What I want is for
to have a length between (and inclusive) 1 and 10, if not reselect the
making it ready for another user input.

The code responds well for an input less than 1 but fails to recognise any input larger than 10 characters. I can't see what i'm doing wrong?

Answer Source

Firstly, don't call Focus. The documentation clearly states, don't call Focus. If you want to focus a control, you call its Select method.

You don't need to call either though. You should be handling the Validating event and if the control fails validation, you set e.Cancel to True and the control will not lose focus in the first place.

If myTextBox.TextLength < 1 OrElse myTextBox.TextLength > 10 Then
    'Validation failed.
    e.Cancel = True
End If
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download