2

I am trying to validate the number of characters placed inside a TextBox 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.") TextBox5.Focus() TextBox5.SelectAll() Else 'do whatever End If 

What I want is for TextBox5 to have a length between (and inclusive) 1 and 10, if not reselect the TextBox 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?

2
  • 2
    Have you tried removing the Not part Commented Jun 20, 2016 at 13:15
  • You said "If it's not below 2 or above 9", every number 2 or above will pass the if statement. Commented Jun 20, 2016 at 13:27

3 Answers 3

3

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. myTextBox.SelectAll() e.Cancel = True End If 
Sign up to request clarification or add additional context in comments.

Comments

0

From what I can understand, this should do the trick.

NOTE There are a few different ways to achieve this task, however from there sample code you have shown, this should be fine.

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If TextBox5.Text.Length < 1 Or TextBox5.Text.Length > 10 Then MsgBox("Invalid date entry. Use the the following format: DD-MM-YYYY.") TextBox1.SelectAll() Else MessageBox.Show("date accepted...") End If End Sub 

I have this triggering from a button click event.

Comments

0

There are 2 things you must do:

  1. on properties set to maxlength=10 and
  2. handle on KeyPressEventArgs

like this:

Private Sub res_pin_KeyPress(sender As Object, e As KeyPressEventArgs) Handles res_pin.KeyPress If e.KeyChar = Chr(13) Then If Me.res_pin.Text.Length < 6 Then e.Handled = True Else Me.res_deposit.Focus() End If End If End Sub 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.