0

I have an amount field which always is going to be positive number without decimal points like 10000, 1200, 10, 40 etc. I am using the code below to check for a valid amount.

if (!preg_match('/^[1-9][0-9]*$/', $_POST['amount'])) {
    $error[] = 'Invalid amount';
}

Is it right. And, do i need to check for empty post amount using empty function of php separately or does above preg_match also checks for empty string amount.

fabrik
  • 13,237
  • 8
  • 54
  • 69
Kuldeep Thakur
  • 125
  • 1
  • 10
  • No, you don't need to check for empty string. Your current regex forces one digit to exist. – revo Sep 25 '18 at 10:04

2 Answers2

2

Why not simply use filter_var(), like:

if (!abs(filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT))) {
    $error[] = 'Invalid amount';
}
fabrik
  • 13,237
  • 8
  • 54
  • 69
0

I would compare the string to itself when converted to the absolute int value. It is more readable and maintainable.

if ($_POST['amount'] !== abs(intval($_POST['amount']))) {
    $error[] = 'Invalid amount';
}
Barry
  • 3,109
  • 7
  • 20
  • 40