Forum Moderators: coopster & phranque

Message Too Old, No Replies

Making sure that user enters a numerical value in field

         

dreaming of nascar

7:22 am on Aug 5, 2003 (gmt 0)

10+ Year Member



I have a text box that the user is supposed to enter a dollar amount in. I want to check in my script to make sure that they enter a numerical value only. I know just about how to do it, I think, but it isn't working like I'd hoped. Thanks in advance!

D O N

Here is the code I have now:
if ($amount!~ /[^\d]/){
throw an error
}

I got this line (/[^\d]/) from another website.

moltar

8:03 am on Aug 5, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




if ( $amount !~ /\d+/ ) {
give error
}

or you can also allow users to enter cents


if ( $amount !~ /\d+\.?\d{0,2}/ ) {
give error
}

Storyteller

9:06 am on Aug 5, 2003 (gmt 0)

10+ Year Member



dreaming of nascar, why not use CGI::Validate module from CPAN?

moltar, your code will pass any string that contains a digit. Not exactly what I'd call validation.

sugarkane

9:34 am on Aug 5, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



if ($amount!~ /[^\d]/)

That's a double negative - it's saying "if $amount doesn't match anything which isn't a digit, then..."

The regex below will throw an error if $amount doesn't consist of one or more digits only:

if ($amount!~ /^\d+$/ ) {
&throw_an_error
}

moltar

5:30 pm on Aug 5, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thats right, Storyteller, it was 3.30am when I wrote this. Sorry guys, my bad, of course it should contain ^$.