borderAndreaVB free resources for Visual Basic developersborder

borderAndreaVB Visual Basic and VB.NET source code resources - Copyright © 1999-2007 Andrea Tincaniborder

AndreaVB | Forum | News | Downloads | Register | Help | Member List | Statistics | Search | PM | Profile

Print This Topic
Previous Topic (Number Sorting)Next Topic (why should one move to .Net platform ?) New Topic New Poll Post Reply
AndreaVB Forum : VB General : Input Validation in VB6
Poster Message
timmay
Level: Guest


icon Input Validation in VB6

Hey guys, Im a total newb to coding and basically i cant code.
But i have this close to finished program and i just need one last thing in it.
Right, the user inputs a number between 1 and 49 and it will display an error message if the user puts anything over 49 and under 1 but it just crashes if the user inputs a letter or an ascii symbol. Do any of you know the code so it will check for a letter and give an error message if one is found?

19-03-2004 at 07:35 PM
| Quote Reply
JLRodgers
Level: Moderator

Registered: 04-04-2002
Posts: 1616
icon Re: Input Validation in VB6

It's a textbox isn't it?

Well... you could do something like this (it'd be easier to prevent letters from being entered than to strip/warn the user after the fact)


    Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
    Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
    Private Const GWL_STYLE = (-16)
    Private Const ES_NUMBER = &H2000&


'/////////////////////////////////
'// MakeNumericTextbox
Public Sub MakeNumericTextbox(ByRef theTextBox As TextBox, Optional ByVal MakeNumeric As Boolean = True)
    Dim CurStyle As Long
    Dim NewStyle As Long

' Get the current style, so we don't lose anything
    CurStyle = GetWindowLong(theTextBox.hwnd, GWL_STYLE)

    If MakeNumeric Then
       CurStyle = CurStyle Or ES_NUMBER
    Else
       CurStyle = CurStyle And (Not ES_NUMBER)
    End If

' Set the new style
    NewStyle = SetWindowLong(theTextBox.hwnd, GWL_STYLE, CurStyle)
    
' Refresh it... just in case
    theTextBox.Refresh
End Sub

'then just:
MakeNumericTextbox Text1



textboxes have a lostfocus & validate that you can check for proper values then....

and you can set the max size of the textbox to "2" so that 99 would be the largest number


[Edited by JLRodgers on 19-03-2004 at 01:53 PM GMT]

____________________________
Everywhere's Local (classifieds, job postings, & more for everycity in the world - user entered)

19-03-2004 at 07:52 PM
View Profile Send Email to User Show All Posts Visit Homepage | Quote Reply
vbgen
Level: Moderator

Registered: 10-10-2002
Posts: 876
icon Re: Input Validation in VB6

quote:
timmay wrote:
Hey guys, Im a total newb to coding and basically i cant code.
But i have this close to finished program and i just need one last thing in it.
Right, the user inputs a number between 1 and 49 and it will display an error message if the user puts anything over 49 and under 1 but it just crashes if the user inputs a letter or an ascii symbol. Do any of you know the code so it will check for a letter and give an error message if one is found?




'validates if key entered is a NUMBER
' if it isn't a number, function rejects the key entered
'how to use.... durng keypress event
'Keyascii = validateNumber(keyascii)
Public Function ValidateNumber(Source) As String
    Select Case Chr(Source)
        Case "0" To "9"
        Case Else
            If Source <> 8 Then
                ValidateNumber = 0
                Exit Function
            End If
    End Select
        'because this function should return the character pressed
        ValidateNumber = Source
End Function


now, to ensure that user can only enter up to two digits


'put this code in any event like LostFocus,
'KeyUp, Change... you know.
    If CInt(Text1.Text) < 1 Then
        MsgBox "Please Enter a number between 1 and 49. Thank you."
        Text1.Text = ""
    Else
    If CInt(Text1.Text) > 49 Then
        MsgBox "Please Enter a number between 1 and 49. Thank you."
        Text1.Text = ""
    End If
    End If


i hope this helps...  

____________________________
Been busy trying to take a second degree <--it's not working out...
20-03-2004 at 05:56 PM
View Profile Send Email to User Show All Posts | Quote Reply
timmay
Level: Guest

icon Re: Input Validation in VB6

Yay now it dosent accept any letters at all. But i discovered one thing that isnt too important but id rather it was fixed. Empty space crashes it in the same way a letter used too. So if a user is to open up the program and not enter any numbers and hit start then it will crash. Is there any code to deal with empty spaces?

P.S thanks for the other code guys it helped.  

21-03-2004 at 01:06 AM
| Quote Reply
Goran
Level: Moderator

Registered: 16-05-2002
Posts: 1681
icon Re: Input Validation in VB6

if Text1.Text="" then
    MsgBox "Please Enter a number between 1 and 49. Thank you."
    Exit Sub
End If


If a user can enter space in your textbox, then you can use trim function:

If Trim(Text1.Text)="" then

..............................

____________________________
If you find the answer helpful, please mark this topic as solved.

21-03-2004 at 02:34 AM
View Profile Send Email to User Show All Posts | Quote Reply
JLRodgers
Level: Moderator

Registered: 04-04-2002
Posts: 1616
icon Re: Input Validation in VB6

You could just put a "1" (or whatever "default" value the program would use for the box) in the form_load event

Private Sub Form_Load
    Text1.Text = "1"
End Sub

' Then in a lostfocus/validate... or change (but could have weird effects...
Private Sub Text1_LostFocus()
' If Trim(Text1.Text) ="" if you allow the space character but don't think so
    If Text1.Text = "" Then
    ' Enter the default value/whatnot (like given by goran)
    End If
End Sub


Of course... it could be just as easy if not easier to use a combobox... (the code if you'd want it...)

' Set the combobox style to "2 - Dropdown List" in the properties
Private Sub Form_Load()
    Dim i as Integer

    Combo1.Clear
    For i = 1 to 49
        Combo1.AddItem i
    Next
    Combo1.ListIndex = 0
End Sub
' Combo1.Text = the string for the number



[Edited by JLRodgers on 20-03-2004 at 09:23 PM GMT]

____________________________
Everywhere's Local (classifieds, job postings, & more for everycity in the world - user entered)

21-03-2004 at 03:20 AM
View Profile Send Email to User Show All Posts Visit Homepage | Quote Reply
timmay
Level: Guest

icon Re: Input Validation in VB6

Ok great ive got the lostfucus working and it now pops up saying "enter a number" thanks!

    

But whenever the cursor is not bleeping away in a box (like just after ive clicked the "about" button and closed the popup message "about" brings) and i hit start the program crashes. Sorry to keep bugging you guys but im trying to make this real robust  

21-03-2004 at 04:15 AM
| Quote Reply
timmay
Level: Guest

icon Re: Input Validation in VB6

AHA! its ok ive figured it out now. Itll automatically put a default number in FOR the user every single time its left empty so now theres no way to crash it

21-03-2004 at 04:48 AM
| Quote Reply
RayZore
Level: Scholar

Registered: 22-08-2003
Posts: 34
icon Re: Input Validation in VB6

Hi All

Prob past sell by date and not checked, but just to throw my hat into the ring:

'Wot no error trapping?
' Not good to use defaults if data
'entered is bogus rather use validation and error trapping

'My solution:
'Use code to validate keystrokes (wot the gurus said about
'keydown/up event ). but what happens if user cuts and pastes
'data into txtbox. They do the darndest things, bless 'em.

'DT: All command buttons etc set property Causes validation = true

Private sub Text1_Validate(Cancel as boolean)

Dim blnvalidpass as boolean
On error goto Exit_sub

blnvalidpass = false

if isnumeric(text1) then
blnvalidPass = true
ElseIF len(trim(text1)) = 0 then
blnvalidPass = true
text1.text = 0 'Default value
Else
msgbox("You did not enter the correct data dumbass")
'code to clear reset textboxes
End if

Exit_Sub:
Cancel = not(blnvalidpass)
Exit sub

command buttons click event:

Dim blnvalidpass as boolean
On error Goto Err_Sub

blnvalidpass = false
'Test data in text1 etc should/will be caught by the validate
' event
'but rather safe then sorry
'Note :might be better to code into  
'function that returns true or false


if isnumeric(text1) then
blnvalidPass = true
ElseIF len(trim(text1)) = 0 then
blnvalidPass = true
text1.text = 0 'Default value
Else
blnvalidpass = false
end if

if blnvalidpass then
'Do what ever you do with data from text1
end if

Exit_Sub:
'Code to clear & reset textboxes etc
exit sub

Err_sub:
msgbox("You did not enter the correct data dumbass" & vbnewline & "Now all your input will be tossed")
'or words to that effect
Resume Exit_Sub

End sub






[Edited by vbgen on 05-04-2004 at 01:58 AM GMT]

____________________________
I'd rather be fishing

26-03-2004 at 09:54 AM
View Profile Send Email to User Show All Posts | Quote Reply
fabulous
Level: VB Guru


Registered: 03-08-2002
Posts: 439
icon Re: Input Validation in VB6

Here is another option which I find useful in a number of situations.

-Press Ctrl+T in your IDE to get the components dialog up. Select Microsoft Windows Common Controls 2.
-Close the dialog box and place an up down control on your  form.
-Right click the updown control and select properties to bring up its property pages
-Go to the Buddy tab and check the autobuddy check box if there is one text box, otherwise type the name of the 'Buddy' control for this updown - the buddy control is the one that will be affected by the updown controls events.
-Select the text property for the buddy property
-Go to the scrolling tab and enter you valid ranges and select wrap so that if the user tries to go above or below the max/min (s)he will be taken to the other extreme (which is still valid).
-Specify you increment and then click OK to save this info
-On your form, select the control which is the buddy control (you will notice that the updown control is now next to it)
-If it is a text box (which I am assumin it will always be) go to the properties window and set the Locked property to true. This stops the user from entering any value into the textbox.
-Go to the text property and type the default value so that the program starts with something valid.

Run the program to see how it is now. There can be no invalid value for as long as your code behaves itself because all changes can come from the updown control and your code and nothing else.

This might be overkill for this example because the range is a little big but I put this up as an alternative option that eliminates the need for validation code and error messages. In essence, it totally eliminates invalid input and that way you get you program done much quicker, less code to worry about and your user will not have to be frustrated by re-entering any data. And greatest of all for me, there will be one less error message.

I hope someone finds that useful. Happy coding.

____________________________
My boss is a Jewish Carpenter (Jesus Christ)


Brain Bench Certified VB.NET Developer

27-03-2004 at 07:12 AM
View Profile Send Email to User Show All Posts Visit Homepage | Quote Reply
neutrall
Level: Master


Registered: 28-03-2004
Posts: 122
icon Re: Input Validation in VB6

Here's a easy way to ensure that the person enter a value between 1 and 49, and you can force the caption until the number is entered.

Private Sub TXT1_LostCaption()

dim Tmp as integer

tmp = -1

'If value is numeric
if isnumeric(txt1.text) then
  tmp = cint(txt1.text)
  'If value is lower than 1
  if tmp <= 0 then
    tmp = -1
    msgbox ("Number must be between 1 or 49")
  'If value is hight than 49
  elseif tmp >= 50 then
    tmp = -1
    msgbox ("Number must be between 1 or 49")
  end if
end if

'Force Focus back on the textbox if a invalid number is entered
if tmp = -1 then
  txt1.setfocus
end if
end sub


Or you may just take out the validation code from the textbox, and place it in a Validation button. By doing so, you can take out the code to force the focus back.

Daniel B.



____________________________
A Stick give a wise man something to think about... and a fool, something to put in is mouth.

29-03-2004 at 12:20 AM
View Profile Send Email to User Show All Posts Visit Homepage ICQ | Quote Reply
AndreaVB Forum : VB General : Input Validation in VB6
Previous Topic (Number Sorting)Next Topic (why should one move to .Net platform ?) New Topic New Poll Post Reply
Surf To:


Not Logged In? Username: Password: Lost your password?
Partners: Download Actual Software | Free Software Download
borderAndreaVB free resources for Visual Basic developersborder

borderAndreaVB Visual Basic and VB.NET source code resources - Copyright © 1999-2007 Andrea Tincaniborder