Wrox Programmer Forums
|
PHP How-To Post your "How do I do this with PHP?" questions here.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the PHP How-To section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old March 10th, 2004, 04:19 AM
Authorized User
 
Join Date: Oct 2003
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default regexp problem

i have a textbox that will let user to enter the product's price but i have to check if user enter two decimal meaning

12.30, 9.55, 1478.90 is true
12.3, 9.568, 1478.9807 is false

function validdecimal(textbox)
{
if ( /[^0-9]/.test(textbox.value) )
{
alert("Please enter string");
textbox.select();
textbox.focus();
}
}

How can i change the function above to check if the user enter the right price?

 
Old March 10th, 2004, 04:43 AM
richard.york's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

I'd use two functions..

Code:
<?php

function is_price($value)
{
    return (is_numeric($value))? round($value, 2) : FALSE;
}

echo is_price(3.456).'<br />';
echo is_price(3.45).'<br />';
echo is_price('doh');

// Or a better implementation

if (FALSE === ($value = is_price(3.456)))
{
    echo 'You did not enter a valid number';    
}
else
{
    echo $value.' is a valid number';    
}

?>
This will gaurantee that no matter what the value, it will return a value rounded to two decimal places and verify that the value provided is a number.

hth,
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
 
Old March 10th, 2004, 04:54 AM
richard.york's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Oh -- you're using JavaScript...
(This is a PHP forum BTW)

You can do something similar with JS though... here is a JavaScript equivilant to the PHP.

function is_price(value)
{
    return (isNaN(value))? FALSE : Math.round(value*100)/100;
}

hth,
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::





Similar Threads
Thread Thread Starter Forum Replies Last Post
RegExp Problem Abbas Classic ASP Professional 0 August 2nd, 2006 10:48 AM
RegExp crmpicco Javascript How-To 0 July 7th, 2005 05:59 AM
RegExp crmpicco Classic ASP Basics 0 June 6th, 2005 05:54 AM
RegExp Nitin_sharma Javascript 2 November 30th, 2004 07:21 AM
regexp problem godhsf80 Javascript How-To 5 March 11th, 2004 04:38 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.