I have the following php code using the codeigniter framework
$this->form_validation->set_rules('money', 'Money', 'integer|required|xss_clean');
It validates a money field as an integer. How can i validate the field as an integer OR a decimal number.
I guessed it would be something simple like
$this->form_validation->set_rules('money', 'Money', '(decimal||integer)|required|xss_clean');
but it doesnt work!
From the CI Form Validation docs:
is_numeric()could work for you, but it accepts some formats that are very unlike money.is_float()would work, except it will fail on strings and integers.Both these functions are also too lenient in validating a numeric integer or decimal that you would normally accept as a money value. The built in CI
decimal()function requires the decimal point and allows+and-characters.Yeah, I know – not helpful, but hopefully it gets you thinking. The syntax you would like to use will simply not work. I’d suggest creating your own form validation rule for validating money by extending the Form_validation library.
Create the file
/application/libraries/MY_Form_validation.phpSomething like this:
I had written a broken example initially, then I tried writing something that would work and realized that it’s up to you. You may or may not want to allow characters like
$,€,-,+, or decimals beyond two places, or a decimal with only one place, or commas in the digit to separate thousands… Use whatever validation method you see fit.There’s a good example here on money format validation: How to check if an entered value is currency