By gribouillo on
Hello,
I'm at the moment writing a module for durpal 5.1. This module contain a form with a 'textfield' (called 'size' in my case) which should accept only integer.
So I wrote this :
function xxx_form_submit($form_id, $form_values) {
$size = $form_values['size'];
$sizeint = is_int($size);
if ($sizeint == FALSE) {
$sizeerror=1;
}
if ($sizeerror==1) {
drupal_set_message($message = "The size you entered seems to be wrong..., ERROR -> size is $size", $type = 'error');
}
}
But the problem is that I always get the error "The size you entered..." even if I entered an integer in the textfield 'size'. What's wrong ? Any suggestions ?
Thx for help.
Best Regards,
Guillaume SUDRE
Comments
...
This expression would always return false.
Any PHP variable (or value) is of a certain type.
'blah' is a string.
'23 blah' is a string.
'23' is a string(!).
23 is an integer.
23.5 is a float.
The variable
$sizethat you got from the form is a string. Everything you get from a textfield is a string. Everything the user types is a string. (Yes, it can be converted, later, to an integer.)You don't want to check whether that variable is of the
integertype. You want to check whether it's numeric. That is, whether it's a string that looks like a number (or... whether it's a genuine integer, or a float). And for this you should use theis_numericfunction instead (instead ofis_int).See:
http://php.net/is_int
http://php.net/is_numeric
(You have some "stylistic" problems in your code, but first let's correct your bug.)
Because it is a string
Because it is a numeric string. Use is_numeric instead.
Many PHP functions are documented on PHP.net. See for example the available documentation on is_int.
In addition, validate input in [form_id]_validate, not [form_id]_submit; simply do the is_numeric test and use form_set_error('size', t('The error message')); eg:
If you are certain you need an integer, use a regular expression / ctype_digit, don't forget to bound check, then convert to an integer (int_val).
However, don't use user input directly in output; read Writing secure code esp. Handle text in a secure fashion.
One more point; this is PHP, not Python, so the following will do for a function call:
PS If you wrap your code in <?php ?> tags on this site, you'll get syntax highlighting for free. While taking the liberty to do so, I also indented the code.
--
The Manual | Troubleshooting FAQ | Tips for posting | How to report a security issue.
It works :)
Thank you, you both for your help. I wrote this :
And now it works perfect. It was exactly what I wanted. :)
I didn't know the xxx_validate and the "ctype_digit" function.
Best Regards,
Guillaume
Thanks alot.. I've been
Thanks alot.. I've been looking for this too.
Now it works fine for me.
Cheers!