Forum Moderators: coopster

Message Too Old, No Replies

Validating an income field

         

big_jimmi

12:47 pm on Jun 4, 2007 (gmt 0)

10+ Year Member



Hi guys.

I'm trying to validate an income field on a web form. I'm having problems working out how to say allow 0 or 1 decimal point in the field - i.e someone could input 800 or 800.00 not 800..00. Also if someone does use a decimal point a number must follow it - ie 800.00 not 800.

This is what im using at the min (which doesnt do the above)

if ($_POST['earningsfirst'] == '') {
$error_msg['earningsfirst'] = '<div class=message>Please enter your earnings</div>';
}

if(!empty($_POST['earningsfirst'])) {
if (!preg_match('/^[0-9\.]+$/' , $_POST['earningsfirst'])){
$error_msg['earningsfirst'] = '<div class=message>Invalid character in main earnings. </div>';
}
}

any ideas?

thanks in advance

topr8

1:03 pm on Jun 4, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



what about the built in php function

is_numeric()

dreamcatcher

1:21 pm on Jun 4, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can also use the ctype functions:

if (!ctype_digit [php.net]($_POST['earningsfirst']))
{
//error
}

or the character class [[:digit]]

if (!ereg("^[[:digit:]]+$", $_POST['earningsfirst']))
{
//error
}

dc

big_jimmi

3:17 pm on Jun 4, 2007 (gmt 0)

10+ Year Member



thanks for the replies.

Ive tried ctype_digit and [:digit:} but i need to allow for the user inputting income with and without a decimal point - which i can do BUT I need to make sure if an decimal point is used then only one can be inputted and it must be followed by a number ie

800 , 800.00

NOT

800. , 8.00.0 , 8.0.

Really struggling with this - any more ideas?

Thanks

coopster

10:01 pm on Jun 6, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Try this pattern in your preg_match:
$pattern = "/^\d{0,9}(\.\d{1,2})?$/";