Monday, May 23, 2011

Validating the Price

It will check that given text is valid price or not.

Pattern Rules:
1: Supports 0.01 to 
0.99
2: Supports 1.00 to ########.99
3: 0, 0.00, None numeric chars or at least two . (dots) are not allowed.
4: .## (float/precision points) are optional.

/**
 * is_price_valid ()
 * Checkout that given price is valid or not.
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string   $price    String to check.
 * @return   bool     True on valid, False on invalid.
 */ 

function is_price_valid ($price)
{
    if (!
is_string ($price)
        || 
trim ($price) == '')
            return 
false;
  
    
//** Pattern copyright 2011 Junaid Atari
  
    //** Upto 8 chars allowed before . (dot).
    //** Support 2 percisions after . (dot).
    
return preg_match ('/^0\.([0-9][1-9]|[1-9][0-9])'.
                       
'|[1-9][0-9]{0,7}(\.[0-9][0-9])?$/x'$price) == 0
               
false
               
true;
}
/*
 +========================================
 | EXAMPLE
 +========================================
*/ 

echo "Is valid price? " . (is_price_valid ('111') ? 'Yes' 'No');
/* 
 +======================================== 
 | EXAMPLE 
 +======================================== 
*/ 
# Is valid price? Yes

# 1, 0.01, 121.99, 1.00 are valid prices.