在开发过程中,多多少少都会遇到金额值得校验,被测试员撵着屁股走,每次都给我提这个问题,不善其扰。简单正则已经无法做到排除-0,0,0.00,01,0001 等值。因此写一个通用函数来判断是否为正确得金额格式:
/**
* 金额校验函数
* @param $value
* @param bool $isZero
* @param bool $negative
* @return bool
*/
function isAmount($value, $isZero=false, $negative=false){
// 必须是整数或浮点数,且允许为负
if (!preg_match("/^[-]?\d+(.\d{1,2})?$/", $value)){
return false;
}
// 不为 0
if (!$isZero && empty((int)($value*100))){
return false;
}
// 不为负数
if (!$negative && (int)($value * 100) < 0){
return false;
}
return true;
}