PHP form validation where value is not null
775
When attempting to validate a field, it doesn't seem to work. I need to only perform!is_numeric
when$postcode
is notnull
. I do have client side validation, but I want to ensure that I have server side validation too.
code:
else if(!is_null($postcode) && !is_numeric($postcode))
{
$msg_to_user = '<br /><br /><h4><font color="FF0000">Postcode must be a numeric value.</font></h4>';
}
Answer
Solution:
maybe you want to use empty() function on strlen() function because is_null() checks NULL value. If $postcode is == "" it's not NULL.
than you can use
or
or
As specified in the link, if you want to use is_null, is better to use $postcode !== NULL. Much faster
Answer
Solution:
Assuming
$postcode
comes from either a$POST
or$GET
, it always is a string.!is_null()
will, therefore be FALSE, regardless:You could revert to using
empty()
, which is more liberal. However, PHP is utterly inconsistent and weird when it comes to these checks. For example,empty()
will returnFALSE
for 0 too. Yup.A much better approach, is to do some sort of "duck-typing". In your case: when it can be converted to a numeric value, do that and use it. Then leave it to the language to determine what it considers "number-ish" enough to convert.
So:
And last, off-topic: a heed of warning about your business assumptions: postcodes are not always numeric. Yes, in the US most are. But there are more countries out there (saying this as a EU-citizen who comes way too often about sites that assume everyone is an average-US-citizen)
Answer
Solution:
Try this
Hope this helps