Forum Moderators: coopster
I have an input field in my form that inserts data into the database.
"Postage cost"
I need the user to only be able to enter dollar amounts in the form of 0.00, 1.50 etc
I do not want them to be able to enter $ signs and or text, only the dollar amounts.
I am currently using this code but it wont let you put in '0' as '0.00'.
[PHP]// Check that the postage field has been filled in.
if (empty ($postage)) {
$errors[] = 'Please enter a postage / delivery amount.<br />';
}
[/PHP]
[PHP]// check that the postage is in the correct format - no dollar signs
if (!is_numeric($postage)) {
$errors[] = 'Please input the postage in the form 123.45, without any other symbols.<br/>If postage is free, please enter 0.00<br><br>';
}[/PHP]
The above code is something I quicky added in, but my client wants to allow the users to enter '0' or leave it blank which in those cases would mean that $postage = 0.00
Any advice would be greatly appreciated.
if (isset($postage) && ereg('^[0,9]{1,3}(\.)[0-9]{1,2}$', $postage)){
//-> It's good go process (or set back to $postage)
}elseif (!isset($postage)){
//-> Postage is blank set to 0.00
$postage = '0.00';
}else{
//-> There's a problem set error
$errors[] = 'Please input the postage in the form 123.45, without any other symbols.<br/>If postage is free, please enter 0.00<br><br>';
}
On both the client side and the server side (in case the user has JavaScript disabled) you can first strip any dollar signs and commas before running the value against your regex.
The only difference that I show here, justgowithit, is that I also make the decimal point and decimal place values optional.
if ($postage &&!preg_match("/^\d{0,9}(\.\d{0,2})?$/", $postage)) {
$errors[] = 'The postage field accepts monetary values only.';
} else {
$postage += 0; // convert to numeric value of zero
}