473,396 Members | 2,002 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

viusal basic input validation integer

Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?

isNumeric() checks for a numeric value .. but does not notify of numbers
with decimal places
inputBox returns a string so I could check for decimal point??? this seems
like overkill

The value returned can be asigned into an Integer type and then a Single
type ... the two can be compared .. but still this does not complain about
numbers with decimal places if the fractional part is zero

what is the simple solution?

cw
Feb 28 '06 #1
27 35887
code_wrong wrote:
Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?


Use a masked input box that rejects invalid entries at the keystroke.

Look up "masked input" - there were lots of options for VB6. 6 years ago.

And upgrade to a dynamic OO language as soon as you can. VB6 will bring you
down.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Feb 28 '06 #2

"Phlip" <ph*******@gmail.com> wrote in message
news:ia******************@newssvr30.news.prodigy.c om...
code_wrong wrote:
Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?


Use a masked input box that rejects invalid entries at the keystroke.

Look up "masked input" - there were lots of options for VB6. 6 years ago.

And upgrade to a dynamic OO language as soon as you can. VB6 will bring
you
down.


unfortunately I am restricted to using inputbox() ... why? .. if I change
the method for input now, the students will likely will be traumatised ..
these are very early days
Feb 28 '06 #3
> Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?


Here are two functions that I have posted in the past for similar
questions..... one is for digits only and the other is for "regular"
numbers:

Function IsDigitsOnly(Value As String) As Boolean
IsDigitsOnly = Len(Value) > 0 And _
Not Value Like "*[!0-9]*"
End Function

Function IsNumber(ByVal Value As String) As Boolean
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9.]*" And _
Not Value Like "*.*.*" And _
Len(Value) > 0 And Value <> "." And _
Value <> vbNullString
End Function

Here are revisions to the above functions that deal with the local settings
for decimal points (and thousand's separators) that are different than used
in the US (this code works in the US too, of course).

Function IsNumber(ByVal Value As String) As Boolean
Dim DP As String
' Get local setting for decimal point
DP = Format$(0, ".")
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
Not Value Like "*" & DP & "*" & DP & "*" And _
Len(Value) > 0 And Value <> DP And _
Value <> vbNullString
End Function

I'm not as concerned by the rejection of entries that include one or more
thousand's separators, but we can handle this if we don't insist on the
thousand's separator being located in the correct positions (in other words,
we'll allow the user to include them for their own purposes... we'll just
tolerate their presence).

Function IsNumber(ByVal Value As String) As Boolean
Dim DP As String
Dim TS As String
' Get local setting for decimal point
DP = Format$(0, ".")
' Get local setting for thousand's separator
' and eliminate them. Remove the next two lines
' if you don't want your users being able to
' type in the thousands separator at all.
TS = Mid$(Format$(1000, "#,###"), 2, 1)
Value = Replace$(Value, TS, "")
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
Not Value Like "*" & DP & "*" & DP & "*" And _
Len(Value) > 0 And Value <> DP And _
Value <> vbNullString
End Function

Rick
Feb 28 '06 #4
code_wrong wrote:
Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?

isNumeric() checks for a numeric value .. but does not notify of numbers
with decimal places
inputBox returns a string so I could check for decimal point??? this seems
like overkill

The value returned can be asigned into an Integer type and then a Single
type ... the two can be compared .. but still this does not complain about
numbers with decimal places if the fractional part is zero

what is the simple solution?

cw


What you can do on a text box control that is being used for only
numbers is use the Keypress Event and check the key being pressed. If
it's a numeric key 0-9, you accept the keypress. If the key is not a
numeric key 0-9, the you cancel or don't accept the keypress. I recall
ASCII code 0 or something like that cancels key-code from a key press so
that it's not accepted.

You just write a Keypress event routine that accepts numeric keys or
possibly a control key like the ESC-Key, Backspace-Key or ( Tab-key set
focus to the next control), take the appropriate actions on the
control-keys, cancel any key that's not 0-9 and only accept the 0-9 keys.

Duane :)
Feb 28 '06 #5
> What you can do on a text box control that is being used for only
numbers is use the Keypress Event and check the key being pressed. If
it's a numeric key 0-9, you accept the keypress. If the key is not a
numeric key 0-9, the you cancel or don't accept the keypress. I recall
ASCII code 0 or something like that cancels key-code from a key press so
that it's not accepted.

You just write a Keypress event routine that accepts numeric keys or
possibly a control key like the ESC-Key, Backspace-Key or ( Tab-key set
focus to the next control), take the appropriate actions on the
control-keys, cancel any key that's not 0-9 and only accept the 0-9 keys.


You can't take appropriate action on "true" control keys in the KeyPress
event; that requires the KeyUp or KeyDown event. And if you don't handle all
of the keystrokes that allow a user to Paste data (and the Mouse events that
allow it too), then your user will be able to Paste non-digits into the
TextBox. And, after all of that, I think you will still have missed one or
two places where the user can initiate a Paste operation.

Rick
Feb 28 '06 #6
Rick Rothstein [MVP - Visual Basic] wrote:
What you can do on a text box control that is being used for only
numbers is use the Keypress Event and check the key being pressed. If
it's a numeric key 0-9, you accept the keypress. If the key is not a
numeric key 0-9, the you cancel or don't accept the keypress. I recall
ASCII code 0 or something like that cancels key-code from a key press so
that it's not accepted.

You just write a Keypress event routine that accepts numeric keys or
possibly a control key like the ESC-Key, Backspace-Key or ( Tab-key set
focus to the next control), take the appropriate actions on the
control-keys, cancel any key that's not 0-9 and only accept the 0-9 keys.

You can't take appropriate action on "true" control keys in the KeyPress
event; that requires the KeyUp or KeyDown event. And if you don't handle all
of the keystrokes that allow a user to Paste data (and the Mouse events that
allow it too), then your user will be able to Paste non-digits into the
TextBox. And, after all of that, I think you will still have missed one or
two places where the user can initiate a Paste operation.

Rick


You may be right I don't recall. However, I have used Keyup, Keydown,
Keypress and Mouse events. In the real world or in accounting
appliactions in business solutions in corporations where I have applied
the numeric only solution, it's worked like a champ on pure data entry
applications where the numbers had to be banged in - there is no cutting
and pasting.

It's something the poster is going to have to figure out for his or
herself as to the best approach.

Duane :)

Mar 1 '06 #7
Rick ...

Is not: Not Value Like "*[!0-9]*" ... redundant?

--

Randy Birch
MS MVP Visual Basic
http://vbnet.mvps.org/

Please reply to the newsgroups so all can participate.


"Rick Rothstein [MVP - Visual Basic]" <ri************@NOSPAMcomcast.net>
wrote in message news:-c******************************@comcast.com...
Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?


Here are two functions that I have posted in the past for similar
questions..... one is for digits only and the other is for "regular"
numbers:

Function IsDigitsOnly(Value As String) As Boolean
IsDigitsOnly = Len(Value) > 0 And _
Not Value Like "*[!0-9]*"
End Function

Function IsNumber(ByVal Value As String) As Boolean
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9.]*" And _
Not Value Like "*.*.*" And _
Len(Value) > 0 And Value <> "." And _
Value <> vbNullString
End Function

Here are revisions to the above functions that deal with the local settings
for decimal points (and thousand's separators) that are different than used
in the US (this code works in the US too, of course).

Function IsNumber(ByVal Value As String) As Boolean
Dim DP As String
' Get local setting for decimal point
DP = Format$(0, ".")
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
Not Value Like "*" & DP & "*" & DP & "*" And _
Len(Value) > 0 And Value <> DP And _
Value <> vbNullString
End Function

I'm not as concerned by the rejection of entries that include one or more
thousand's separators, but we can handle this if we don't insist on the
thousand's separator being located in the correct positions (in other words,
we'll allow the user to include them for their own purposes... we'll just
tolerate their presence).

Function IsNumber(ByVal Value As String) As Boolean
Dim DP As String
Dim TS As String
' Get local setting for decimal point
DP = Format$(0, ".")
' Get local setting for thousand's separator
' and eliminate them. Remove the next two lines
' if you don't want your users being able to
' type in the thousands separator at all.
TS = Mid$(Format$(1000, "#,###"), 2, 1)
Value = Replace$(Value, TS, "")
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
Not Value Like "*" & DP & "*" & DP & "*" And _
Len(Value) > 0 And Value <> DP And _
Value <> vbNullString
End Function

Rick
Mar 1 '06 #8

"code_wrong" <ta*@tac.co.uk> wrote in message
news:44**********@mk-nntp-2.news.uk.tiscali.com...
Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?

isNumeric() checks for a numeric value .. but does not notify of numbers with
decimal places
inputBox returns a string so I could check for decimal point??? this seems
like overkill

The value returned can be asigned into an Integer type and then a Single type
... the two can be compared .. but still this does not complain about numbers
with decimal places if the fractional part is zero

what is the simple solution?


"simple solution" is always a relative term in this NG :)

For integers, I would do this test, which deals with fractional entries as well:

Private Sub Command1_Click()
Dim A As Single
Dim B As Long
Dim C As Single
Dim bNum As Boolean
Dim sInput As String

sInput = InputBox("enter an integer", , "0")
bNum = IsNumeric(sInput)
If bNum Then
A = CSng(sInput)
B = CLng(A)
C = CSng(B)
End If
If bNum And C = A Then
MsgBox "good dog, you entered " & B
Else
MsgBox "How is " & sInput & " an integer?"
End If

End Sub

That way, the user can enter 3E7 if they want, a perfectly valid way of entering
30,000,000 :)
Mar 1 '06 #9
Steve Gerrard wrote:
MsgBoxÂ*"HowÂ*isÂ*"Â*&Â*sInputÂ*&Â*"Â*anÂ*integer? "


As a user, seeing sophomoric crap like that get through gives me a very low
opinion of the programmer on the other side.

For the OP; handle errors at keystroke time or at turn-around time (when the
field blurs, or when the current page submits). Then if the error is
complex, write text into a special field on the form. If the error is
simple, beep and turn its field red.

Contact with a user should be as sensitive and gentle as possible, to avoid
looking like the average VB interface.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 1 '06 #10
> Is not: Not Value Like "*[!0-9]*" ... redundant?

No, it is not redundant. You can't test directly like this

Value Like "*[!0-9]*"

because that would match any **single** digit, no matter where it is located
and no matter what the other characters are (digits or not). The only way to
handle this, as you found out, is with the "double negative" approach. For a
string to be composed of all digits, no one of them can be a non-digit. So
we check for that non-digit-ness. And if it is False, then the string is
composed of only digits characters. But we don't want to return False
through the function, so we NOT the expression to turn False into True for
return through the function. As for syntax, the exclamation mark within the
squared brackets says "match all characters **except** for those that
follow".
Mar 1 '06 #11
Phlip wrote:
Steve Gerrard wrote:
MsgBox "How is " & sInput & " an integer?"


As a user, seeing sophomoric crap like that get through gives me
a very low opinion of the programmer on the other side.


He didn't. That stuff is some fabrication of your newsreader. The
 characters don't exist in his original.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>

Mar 1 '06 #12

"Phlip" <ph*******@gmail.com> wrote in message
news:Z2******************@newssvr30.news.prodigy.c om...
For the OP; handle errors at keystroke time or at turn-around time (when the
field blurs, or when the current page submits). Then if the error is
complex, write text into a special field on the form. If the error is
simple, beep and turn its field red.


OP's question was:
"what is the best way to check the User has entered an integer into an
InputBox?"

Followed with a second post stating:
"unfortunately I am restricted to using inputbox() ... "
MsgBox "How is " & sInput & " an integer?"


As a user, seeing sophomoric crap like that get through gives me a very low
opinion of the programmer on the other side.

Contact with a user should be as sensitive and gentle as possible, to avoid
looking like the average VB interface.


Contact with a NG should be as sensitive and gentle as possible, to avoid
looking like you can't tell the difference between the serious code and the lame
NG humor :)

Mar 1 '06 #13

"code_wrong" <ta*@tac.co.uk> wrote in message
news:44**********@mk-nntp-2.news.uk.tiscali.com...

unfortunately I am restricted to using inputbox() ... why? .. if I change
the method for input now, the students will likely will be traumatised ..
these are very early days


num = VAL(Text1.text)
if num*10 / 10 = INT(num*10/10) then debug.print "whole number" else
debug.print "has decimal"

Mar 1 '06 #14
CBFalconer wrote:
Phlip wrote:
Steve Gerrard wrote:
MsgBox "How is " & sInput & " an integer?"

As a user, seeing sophomoric crap like that get through gives me
a very low opinion of the programmer on the other side.


He didn't. That stuff is some fabrication of your newsreader. The
 characters don't exist in his original.


Nor in Phlips reply...
Phlip was referring to the content of the message itself rather than the
garbage characters your client seems to have added.

--
Dean Earley (de*********@icode.co.uk)
i-Catcher Development Team

iCode Systems
Mar 2 '06 #15

"code_wrong" <ta*@tac.co.uk> wrote in message
news:44**********@mk-nntp-2.news.uk.tiscali.com...
Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?

isNumeric() checks for a numeric value .. but does not notify of numbers
with decimal places
inputBox returns a string so I could check for decimal point??? this seems
like overkill

The value returned can be asigned into an Integer type and then a Single
type ... the two can be compared .. but still this does not complain about
numbers with decimal places if the fractional part is zero

what is the simple solution?


Interesting discussion , thanks for the replies.
I have decided to provide students with a pre-defined function of my own
design
please review and improve if you can
the function:

Function isInteger(strVal As String) As Boolean

'if not numeric or decimal point found
If Not IsNumeric(strVal) Or InStr(strVal, ".") Then
isInteger = False
Else
isInteger = True
End If

End Function

Mar 2 '06 #16

"code_wrong" <ta*@tac.co.uk> wrote in message
news:44**********@mk-nntp-2.news.uk.tiscali.com...
Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?

isNumeric() checks for a numeric value .. but does not notify of numbers
with decimal places
inputBox returns a string so I could check for decimal point??? this seems
like overkill

The value returned can be asigned into an Integer type and then a Single
type ... the two can be compared .. but still this does not complain about
numbers with decimal places if the fractional part is zero

what is the simple solution?


Interesting discussion , thanks for the replies.
I have decided to provide students with a pre-defined function of my own
design
please review and improve if you can
the function:

Function isInteger(strVal As String) As Boolean

'if not numeric or decimal point found
If Not IsNumeric(strVal) Or InStr(strVal, ".") Then
isInteger = False
Else
isInteger = True
End If

End Function

Mar 2 '06 #17
> I have decided to provide students with a pre-defined function of my own
design
please review and improve if you can
the function:

Function isInteger(strVal As String) As Boolean

'if not numeric or decimal point found
If Not IsNumeric(strVal) Or InStr(strVal, ".") Then
isInteger = False
Else
isInteger = True
End If

End Function


From a previous post of mine...

I usually try and steer people away from using IsNumeric to "proof"
supposedly numeric text. Consider this (also see note below):

ReturnValue = IsNumeric("($1,23,,3.4,,,5,,E67$)")

Most people would not expect THAT to return True. IsNumeric has some "flaws"
in what it considers a proper number and what most programmers are looking
for.

I had a short tip published by Pinnacle Publishing in their Visual Basic
Developer magazine that covered some of these flaws. Originally, the tip was
free to view but is now viewable only by subscribers.. Basically, it said
that IsNumeric returned True for things like -- currency symbols being
located in front or in back of the number as shown in my example (also
applies to plus, minus and blanks too); numbers surrounded by parentheses as
shown in my example (some people use these to mark negative numbers);
numbers containing any number of commas before a decimal point as shown in
my example; numbers in scientific notation (a number followed by an upper or
lower case "D" or "E", followed by a number equal to or less than 305 -- the
maximum power of 10 in VB); and Octal/Hexadecimal numbers (&H for
Hexadecimal, &O or just & in front of the number for Octal).

NOTE:
======
In the above example and in the referenced tip, I refer to $ signs and
commas and dots -- these were meant to refer to your currency, thousands
separator and decimal point symbols as defined in your local settings --
substitute your local regional symbols for these if appropriate.

As for your question about checking numbers, here are two functions that I
have posted in the past for similar questions..... one is for digits only
and the other is for "regular" numbers:

Function IsDigitsOnly(Value As String) As Boolean
IsDigitsOnly = Len(Value) > 0 And _
Not Value Like "*[!0-9]*"
End Function

Function IsNumber(ByVal Value As String) As Boolean
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9.]*" And _
Not Value Like "*.*.*" And _
Len(Value) > 0 And Value <> "." And _
Value <> vbNullString
End Function

Here are revisions to the above functions that deal with the local settings
for decimal points (and thousand's separators) that are different than used
in the US (this code works in the US too, of course).

Function IsNumber(ByVal Value As String) As Boolean
Dim DP As String
' Get local setting for decimal point
DP = Format$(0, ".")
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
Not Value Like "*" & DP & "*" & DP & "*" And _
Len(Value) > 0 And Value <> DP And _
Value <> vbNullString
End Function

I'm not as concerned by the rejection of entries that include one or more
thousand's separators, but we can handle this if we don't insist on the
thousand's separator being located in the correct positions (in other words,
we'll allow the user to include them for their own purposes... we'll just
tolerate their presence).

Function IsNumber(ByVal Value As String) As Boolean
Dim DP As String
Dim TS As String
' Get local setting for decimal point
DP = Format$(0, ".")
' Get local setting for thousand's separator
' and eliminate them. Remove the next two lines
' if you don't want your users being able to
' type in the thousands separator at all.
TS = Mid$(Format$(1000, "#,###"), 2, 1)
Value = Replace$(Value, TS, "")
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
Not Value Like "*" & DP & "*" & DP & "*" And _
Len(Value) > 0 And Value <> DP And _
Value <> vbNullString
End Function

Rick
Mar 2 '06 #18
code_wrong wrote:
"code_wrong" <ta*@tac.co.uk> wrote in message
news:44**********@mk-nntp-2.news.uk.tiscali.com...
Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?

isNumeric() checks for a numeric value .. but does not notify of numbers
with decimal places
inputBox returns a string so I could check for decimal point??? this seems
like overkill

The value returned can be asigned into an Integer type and then a Single
type ... the two can be compared .. but still this does not complain about
numbers with decimal places if the fractional part is zero

what is the simple solution?

Interesting discussion , thanks for the replies.
I have decided to provide students with a pre-defined function of my own
design
please review and improve if you can
the function:

Function isInteger(strVal As String) As Boolean

'if not numeric or decimal point found
If Not IsNumeric(strVal) Or InStr(strVal, ".") Then
isInteger = False
Else
isInteger = True
End If

End Function


If you have tested it and it works -- it works.

Does it need to be complicated for some reason?

Duane :)
Mar 2 '06 #19

"Rick Rothstein [MVP - Visual Basic]" <ri************@NOSPAMcomcast.net>
wrote in message news:jN******************************@comcast.com. ..
I have decided to provide students with a pre-defined function of my own
design
please review and improve if you can
the function:

Function isInteger(strVal As String) As Boolean

'if not numeric or decimal point found
If Not IsNumeric(strVal) Or InStr(strVal, ".") Then
isInteger = False
Else
isInteger = True
End If

End Function


From a previous post of mine...

I usually try and steer people away from using IsNumeric to "proof"
supposedly numeric text. Consider this (also see note below):

ReturnValue = IsNumeric("($1,23,,3.4,,,5,,E67$)")

Most people would not expect THAT to return True. IsNumeric has some
"flaws"
in what it considers a proper number and what most programmers are looking
for.

I had a short tip published by Pinnacle Publishing in their Visual Basic
Developer magazine that covered some of these flaws. Originally, the tip
was
free to view but is now viewable only by subscribers.. Basically, it said
that IsNumeric returned True for things like -- currency symbols being
located in front or in back of the number as shown in my example (also
applies to plus, minus and blanks too); numbers surrounded by parentheses
as
shown in my example (some people use these to mark negative numbers);
numbers containing any number of commas before a decimal point as shown in
my example; numbers in scientific notation (a number followed by an upper
or
lower case "D" or "E", followed by a number equal to or less than 305 --
the
maximum power of 10 in VB); and Octal/Hexadecimal numbers (&H for
Hexadecimal, &O or just & in front of the number for Octal).

NOTE:
======
In the above example and in the referenced tip, I refer to $ signs and
commas and dots -- these were meant to refer to your currency, thousands
separator and decimal point symbols as defined in your local settings --
substitute your local regional symbols for these if appropriate.

As for your question about checking numbers, here are two functions that I
have posted in the past for similar questions..... one is for digits only
and the other is for "regular" numbers:

Function IsDigitsOnly(Value As String) As Boolean
IsDigitsOnly = Len(Value) > 0 And _
Not Value Like "*[!0-9]*"
End Function

Function IsNumber(ByVal Value As String) As Boolean
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9.]*" And _
Not Value Like "*.*.*" And _
Len(Value) > 0 And Value <> "." And _
Value <> vbNullString
End Function

Here are revisions to the above functions that deal with the local
settings
for decimal points (and thousand's separators) that are different than
used
in the US (this code works in the US too, of course).

Function IsNumber(ByVal Value As String) As Boolean
Dim DP As String
' Get local setting for decimal point
DP = Format$(0, ".")
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
Not Value Like "*" & DP & "*" & DP & "*" And _
Len(Value) > 0 And Value <> DP And _
Value <> vbNullString
End Function

I'm not as concerned by the rejection of entries that include one or more
thousand's separators, but we can handle this if we don't insist on the
thousand's separator being located in the correct positions (in other
words,
we'll allow the user to include them for their own purposes... we'll just
tolerate their presence).

Function IsNumber(ByVal Value As String) As Boolean
Dim DP As String
Dim TS As String
' Get local setting for decimal point
DP = Format$(0, ".")
' Get local setting for thousand's separator
' and eliminate them. Remove the next two lines
' if you don't want your users being able to
' type in the thousands separator at all.
TS = Mid$(Format$(1000, "#,###"), 2, 1)
Value = Replace$(Value, TS, "")
' Leave the next statement out if you don't
' want to provide for plus/minus signs
If Value Like "[+-]*" Then Value = Mid$(Value, 2)
IsNumber = Not Value Like "*[!0-9" & DP & "]*" And _
Not Value Like "*" & DP & "*" & DP & "*" And _
Len(Value) > 0 And Value <> DP And _
Value <> vbNullString
End Function


interesting, you have made a comprehensive study of the flawed isNumeric()
function
I don't understand this aspect of your code : Like "*[!0-9]*" can't find it
in my VB manual.
what's going on there?

cw

Mar 2 '06 #20
> interesting, you have made a comprehensive study
of the flawed isNumeric() function
I had to... I wouldn't have been able to sell the article to the magazine if
I didn't.<g>
I don't understand this aspect of your code :
Like "*[!0-9]*" can't find it in my VB manual.
what's going on there?


Like is an operator used for comparing a text string to a string pattern
(similar to how regular expressions work, but on a much more limited scale).
You should be able to look up the Like Operator in your VB help files. You
can also view the help file for it online at this link

http://msdn.microsoft.com/library/en.../vaoprlike.asp

Anyway, everything inside of the brackets stands for a single character. The
0-9 part indicates the digit characters (ranging for "0" to "9") and the
exclamation sign at the beginning says to consider all characters except for
what follows it. So that means that any character that is not a digit will
match the this pattern. The two asterisks on either side of the brackets
match zero or more characters, no matter what those characters are. So, the
whole expression to the right of the Like operator matches any non-digit, no
matter where it occurs in the text string being examined. The left side of
the Like operator expression (which you left out of your question) is very
important to the construction of functionality of this entire expression.
Here is the part of the original expression that you asked about

Not Value Like "*[!0-9]*"

where Value is the text string being examined. Remember the expression on
the right of the Like operator matches a non-digit anywhere in the string
contained in the Value variable... the Not operator in front of the
expression negates that meaning the entire expression is True when no
non-digit is found in the text string. That condition, no non-digit, means
the expression is composed only of digits. You must use this double-negative
approach to test for this; you cannot not do it directly in any other way.

Rick
Mar 2 '06 #21

"code_wrong" <ta*@tac.co.uk> wrote in message
news:44**********@mk-nntp-2.news.uk.tiscali.com...

interesting, you have made a comprehensive study of the flawed isNumeric()
function


Since Rick posted his IsNumeric post, I will toss in mine as well :)

IsNumeric has one particular purpose, which it does well, so it is not flawed.
Its function is to determine whether or not a particular expression can be
converted to a number without causing an error.

As Rick points out, the test

IsNumeric("($1,23,,3.4,,,5,,E67$)")

returns True, which is correct, because the conversion

X = CDbl("($1,23,,3.4,,,5,,E67$)")

will assign X the value

-1.23345E+70

rather than raising an error.

In case you are curious, the conversion will ignore the commas and $, since they
are allowed in numeric expressions, and it will treat the enclosing parentheses
as an accountant's version of a minus sign.
That gives it -1233.45 E67, which the VB immediate window then displays in
"proper" scientific notation.

IsNumeric is not meant to be, and quite plainly is not, a strict input parsing
function, but is rather a programming tool with which to avoid "Type Mismatch"
errors during conversions steps.
Mar 4 '06 #22
Duane Arnold wrote:
code_wrong wrote:
"code_wrong" <ta*@tac.co.uk> wrote in message
news:44**********@mk-nntp-2.news.uk.tiscali.com...
Visual Basic (not dot net)
what is the best way to check the User has entered an integer into an
InputBox?

isNumeric() checks for a numeric value .. but does not notify of
numbers with decimal places
inputBox returns a string so I could check for decimal point??? this
seems like overkill

The value returned can be asigned into an Integer type and then a
Single type ... the two can be compared .. but still this does not
complain about numbers with decimal places if the fractional part is
zero

what is the simple solution?


Interesting discussion , thanks for the replies.
I have decided to provide students with a pre-defined function of my
own design
please review and improve if you can
the function:

Function isInteger(strVal As String) As Boolean

'if not numeric or decimal point found
If Not IsNumeric(strVal) Or InStr(strVal, ".") Then
isInteger = False
Else
isInteger = True
End If

End Function


If you have tested it and it works -- it works.

Does it need to be complicated for some reason?

Duane :)


It seems to me that a simple cast and cast back can be used for validation:

Function MyIsNumeric(ByVal cand as String) as Boolean
If cand = CStr(CLng(cand)) Then
MyIsNumeric = True
Else
MyIsNumeric = False
End Function

But take that with a grain of salt, I haven't actually tested it.
Mar 14 '06 #23
On Tue, 14 Mar 2006 11:20:21 +0200, Lord Duran <lo********@gmail.com>
wrote:
<snip>
It seems to me that a simple cast and cast back can be used for validation:

Function MyIsNumeric(ByVal cand as String) as Boolean
If cand = CStr(CLng(cand)) Then
MyIsNumeric = True
Else
MyIsNumeric = False
End Function

But take that with a grain of salt, I haven't actually tested it.


It will blow big time - if the String contains 'FRED'

Incidentally you are mis-using the word 'Cast'
- CStr and CLng are are Functions that 'Convert'
( the 'C' stands for Convert - 'Cast' is something entirely different
better not gone into now )

With Error Handling then what you suggest is half way there

IMO the best method is to handle all checking extremely rigorously


Mar 14 '06 #24
> It seems to me that a simple cast and cast back can be used for validation:

Function MyIsNumeric(ByVal cand as String) as Boolean
If cand = CStr(CLng(cand)) Then
MyIsNumeric = True
Else
MyIsNumeric = False
End Function

But take that with a grain of salt, I haven't actually tested it.


You may want to use Val() rather than CLng() as the latter will error
when its not a number.

--
Dean Earley (de*********@icode.co.uk)
i-Catcher Development Team

iCode Systems
Mar 14 '06 #25
> It seems to me that a simple cast and cast back can be used for
validation:

Function MyIsNumeric(ByVal cand as String) as Boolean
If cand = CStr(CLng(cand)) Then
MyIsNumeric = True
Else
MyIsNumeric = False
End Function

But take that with a grain of salt, I haven't actually tested it.


The problem with that approach (whether you use CLng or Val (as Dean
suggested), is it will show as valid a number from that is normally useless
in an input validation scenario (which is what this thread is about). The
reason is because when a programmer uses such routines, they are NOT really
interested in whether the entry is a number; rather the programmer usually
wants the entry to be all digits (such as in a phone number). As an example,
let's say the programmer wanted the user to input a 4-digit number for
whatever reason and, to eliminate the need to check the length of the entry,
he/she sets the MaxLength property of the TextBox being used to accept the
user's entry to 4. Is everything okay then? Nope! Your routine will fail the
programmer for an entry like 12e3 (notice the embedded "e"). Your routine
would return True because 12e3 is a valid number... it is 12000 when
expanded... but note that is a 5-digit number, not 4-digit number as
required, and that would probably screw up the program when it tried to use
it.

Rick
Mar 14 '06 #26
Rick Rothstein [MVP - Visual Basic] wrote:
It seems to me that a simple cast and cast back can be used for


validation:
Function MyIsNumeric(ByVal cand as String) as Boolean
If cand = CStr(CLng(cand)) Then
MyIsNumeric = True
Else
MyIsNumeric = False
End Function

But take that with a grain of salt, I haven't actually tested it.

The problem with that approach (whether you use CLng or Val (as Dean
suggested), is it will show as valid a number from that is normally useless
in an input validation scenario (which is what this thread is about). The
reason is because when a programmer uses such routines, they are NOT really
interested in whether the entry is a number; rather the programmer usually
wants the entry to be all digits (such as in a phone number). As an example,
let's say the programmer wanted the user to input a 4-digit number for
whatever reason and, to eliminate the need to check the length of the entry,
he/she sets the MaxLength property of the TextBox being used to accept the
user's entry to 4. Is everything okay then? Nope! Your routine will fail the
programmer for an entry like 12e3 (notice the embedded "e"). Your routine
would return True because 12e3 is a valid number... it is 12000 when
expanded... but note that is a 5-digit number, not 4-digit number as
required, and that would probably screw up the program when it tried to use
it.

Rick

It's poor programming if that were to happen. That's why one would have
further validation of the inputed data expecting it to be saved and
checking for the validity of data in business rules somewhere else no
complication in UI, except for a simple check for numerics for a given
field.

Duane :)
Mar 15 '06 #27
Rick Rothstein [MVP - Visual Basic] wrote:
It seems to me that a simple cast and cast back can be used for


validation:
Function MyIsNumeric(ByVal cand as String) as Boolean
If cand = CStr(CLng(cand)) Then
MyIsNumeric = True
Else
MyIsNumeric = False
End Function

But take that with a grain of salt, I haven't actually tested it.

The problem with that approach (whether you use CLng or Val (as Dean
suggested), is it will show as valid a number from that is normally useless
in an input validation scenario (which is what this thread is about). The
reason is because when a programmer uses such routines, they are NOT really
interested in whether the entry is a number; rather the programmer usually
wants the entry to be all digits (such as in a phone number). As an example,
let's say the programmer wanted the user to input a 4-digit number for
whatever reason and, to eliminate the need to check the length of the entry,
he/she sets the MaxLength property of the TextBox being used to accept the
user's entry to 4. Is everything okay then? Nope! Your routine will fail the
programmer for an entry like 12e3 (notice the embedded "e"). Your routine
would return True because 12e3 is a valid number... it is 12000 when
expanded... but note that is a 5-digit number, not 4-digit number as
required, and that would probably screw up the program when it tried to use
it.

Rick


I don't know how robust that things is, but your example would not work
here - because CStr(Val("12e3")) = "12000" which is not equal to "12e3"
when comparing strings.
Mar 18 '06 #28

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Gleep | last post by:
Hi PHP coders, I've got an issue I'm stuck with. Imagine there is a large form that has 5 columns and 20 rows. In each row there is a check box - then 4 input fields. I already have the code...
4
by: yai | last post by:
Hi all, I am trying to display close caption with media play by using visual basic.NET I can make it woke on webpage but I don't know how to specific the property...
0
by: joe pribele | last post by:
I have this stored procedure that takes some xml as input. What I need to is use xml as a table so that I can join other tables to the xml and get information back that matches the criteria. I...
9
by: Adam Monsen | last post by:
I kindly request a code review. If this is not an appropriate place for my request, where might be? Specific questions are in the QUESTIONS section of the code. ...
0
by: ntuser_man | last post by:
Howdy I'm trying to validate the content of a csv uploaded to a web page. I imported the csv into a DataSet and now I want to loop through all the elements in the DataSet to validate that each is...
2
by: Jim B | last post by:
I am new to VB.NET and have a question on validating user input from a Text Box. I'm writing a small program where I want to check the users input data and determine if it's an Integer or a...
3
by: redefined.horizons | last post by:
I'm new to C#, (coming from a Java programming background), and I have a question about the correct use of exceptions. My book "Programming C#" by O'Reilly says the following in Chapter 11,...
7
by: Xstrain | last post by:
Having difficulty creating error handling when inputting an integer dvdQuant = input("Enter quantity of DVD: ") how can I get python to return a print "Error Message" if an integer is not...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.