textbox form validation and formatting

I want to be able to create text boxes that-

1. For a phone number are already formated like (555) 555-5555, when you start typeing in the box it automatically moves the cursor along to the next spot.

2. Only allows a date format MM-DD-YYYY

3. Only allows a number value. 1223445

4. Only allows a character value. aabababab


What is that called and any help on how to do it?
LVL 1
NickUAAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

LandyJCommented:
Private Sub txtMyNumberField_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtMyNumberField.KeyPress
   
  With e
    'Valid keys are 0-9 & backspace
    If Not ((Asc(.KeyChar) >= 48 And Asc(.KeyChar) <= 57) Or _
        Asc(.KeyChar) = 8) Then
      .Handled = True
    End If
  End With

End


  Private Sub txtMyDateField_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtMyDateField.KeyPress
    With e
      'Valid keys are 0-9, '/' & backspace
      If Not ((Asc(.KeyChar) >= 48 And Asc(.KeyChar) <= 57) Or _
          Asc(.KeyChar) = 47 Or _
          Asc(.KeyChar) = 8) Then
        .Handled = True
      End If
    End With
  End Sub

  Private Sub txtMyDateField_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtMyDateField.Validating
    'If no date/time was entered, set value to default date/time
    If txtMyDateField.Text = "" Or txtMyDateField.Text = "0" Or InStr(txtMyDateField.Text, "/") = 0 Then txtMyDateField.Text = "1/1/1900"

    'Check to make sure a valid date was entered
    If Not IsDate(txtMyDateField.Text) Then
      ErrorProvider1.SetError(txtMyDateField, "Must enter a valid date or '' for default")
    Else
      ErrorProvider1.SetError(txtMyDateField, "")
    End If
  End Sub

Keep going with the KeyPress and Validating events for each of your fields.  Here's a link to the ASCII character codes: http://www.bbsinc.com/symbol.html -or- http://www.bbsinc.com/iso8859.html

This should get you started.  Hope it helps,
Landy
0
andrewpkCommented:
its called input validation.  sometimes input restriction.

its essentially evaluating the data before the form is processes in order to make sure you're getting valid information.
0
andrewpkCommented:
check out the members of the windows.forms.textbox class.

Its got functions to help you with validation, when to trigger it and such.

Andrew
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

andrewpkCommented:
that would be   system.windows.forms


damn EE and no edits allowed.
0
NickUAAuthor Commented:
landyj
can you help me with your code...I tried it but i am not sure i know how to fire it....what is errorprovider1?

sorry i am a newbie to this.

does anyone know how to make a text box have the "(   )       -       " already in there  so the user just has to enter the numbers and it formats it like (555) 555-5555
0
LandyJCommented:
The code fires when the event occurs:  Keypress fires when the user presses a key when that particular (txtMyNumberField) has the focus, Validating fires when the user sets focus on another control, before focus is set on the new control.  You can check Help to find the order of which event fires when.

ErrorProvider1 is the instance of the ErrorProvider Control.  Again, check Help, but it is a component that indicates errors as the developer defines them.  It places an icon next to the control that indicates there is an error with the data in the control, amoung other things that it can do.  That example is a simple usage of the control.

As for formatting the text box already, there are numerous acceptable ways to process phone numbers.  If you have to have your textbox format the number as the user types it:

Whenever you clear the textbox field: txtMyPhoneField.Text = "(   )    -    "

In the Keypress event for txtMyPhoneField, you'll need restrict entries to numbers (see the txtMyNumberField above)  and then monitor the position of the character being entered.  You'll have to manually position the character in the field and place your special characters (the (, ), and - ) where they are needed.

'Get only the digits the user has entered by removing the (, ) & - characters
Dim iDigits As Integer = Val(Replace(Replace(Replace(txtMyPhoneField.Text, "(", ""), ")", ""), "-", "")).ToString

'Format the field for (999) 999-9999
Select Case Len(iNumDigits.ToString)  'need the .ToString or it will give you the length of an integer data type = 8)
  Case 0
    sender.Text = "(" & sender.Text & "  )    -    "
  Case 1
    sender.Text = sender.text & " )    -    "
  Case  2
    sender.Text = sender.text & ")    -    "
  Case 3
    sender.Text = sender.text & "  -    "
  Case 4
    sender.Text = sender.text & " -    "
  Case ... '(I'll let you have some fun to finish the Case statements)

  Case Else
    if Asc(e.KeyChar) <> 8 Then e.Handled = True  'Throw away all characters after the number is complete, except the BackSpace
End Select

Remember, the newly typed character isn't added to the field until AFTER the KeyPress event, so you'll have to adjust the CASE conditions to make sure you are working with the right position in the mask.  BTW, I'm sure there is a way to set an algorithm to do this, instead of the SELECT CASE structure, but I just don't have the time to work on the looping at the moment.  You should see the pattern that you'll need to go through to create the appearance of an input mask for that field.

Hope this helps,
Landy
0
LandyJCommented:
Oops.  Take that ".ToString" off the end of the Dim iDigits statement

0
NickUAAuthor Commented:
landyj
bear with me...newbie speaking...i understand what is going on i think.  i tried to complete the case statment, but for some reason it is only allowing me to add 1 number, and then when i try to insert another number it puts the characters (  - in there again.

thanks again.
0
LandyJCommented:
Yeah, whoops.  So much for off the top of my head.  Give me a minute to get it correct. Sorry for the confusion.
0
LandyJCommented:
Sorry for that previous mess.  Here's a KeyPress event that will display your phone number mask and format the numbers as they are entered.  Remember to set the TextBox1.Text value to "(   )    -    " whenever you load  or reset the form (textbox)

-Landy


  Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
    TextBox1.Text = "(   )    -    "
  End Sub

  Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    With e
      'Valid keys are 0-9 & backspace, or a final length of 14
      If Not ((Asc(.KeyChar) >= 48 And Asc(.KeyChar) <= 57) Or _
          Asc(.KeyChar) = 8) Or _
          Len(sender.Text.Replace(" ", "")) >= 13 Then  'this also replaces the " " between the Area Code and the Exchange "(999) 999-9999", hence a length of 13 here
        .Handled = True 'Throw away the key stroke
        Exit Sub
      End If
    End With

    Dim idx As Integer
    idx = TextBox1.Text.IndexOf(" ") 'Find the first available position to insert the entered digit
    If idx >= 5 Then
      idx = TextBox1.Text.IndexOf(" ", 6) 'adjust for the space between the Area Code and the Exchange
    End If
    Dim str As String
    With TextBox1
      str = .Text.Substring(0, idx)
      str += CStr(Microsoft.VisualBasic.Val(e.KeyChar))
      str += .Text.Substring(str.Length, .TextLength - (idx + 1))
    End With

    TextBox1.Text = str 'Set the textbox to the built string
    e.Handled = True 'Throw away the keystroke since we manually placed it in the TextBox

  End Sub

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.