Page 1 of 1
Universal empty field validation
Posted: Wed Sep 28, 2005 3:58 pm
by Ree
Is there a universal way to check if the submited field was empty? empty($_POST['field']) isn't universal, as it misses some values, for example, '0'.
Posted: Wed Sep 28, 2005 4:01 pm
by Charles256
but a variable being equal to 0 could be significant:-D
Posted: Wed Sep 28, 2005 5:37 pm
by Maugrim_The_Reaper
Code: Select all
if(!isset($_POST['field']) || $_POST[field] == '')
May work in many circumstances when testing a single field - aren't POST integers passed as strings initially? Hence using is_numeric() rather than is_int() to check for numbers? I think so...
Posted: Wed Sep 28, 2005 5:44 pm
by Jim_Bo
Hi,
another option is:
Code: Select all
if ((!$first_name) || (!$last_name)) {
echo "Ops you missed required fields";
} else {
continue with script
}
hth
Posted: Wed Sep 28, 2005 5:46 pm
by Maugrim_The_Reaper
Except you'd need to enable register_globals unless you intend them to reflect the full POST superglobal reference?
Posted: Wed Sep 28, 2005 6:08 pm
by Jenk
Code: Select all
<?php
if (isset($_POST['var']) && $_POST['var'] != '') {
//do it..
}
else {
//don't do it..
}
?>
Posted: Wed Sep 28, 2005 9:27 pm
by qads
Code: Select all
function check_field($value)
{
$value = trim($value);
return (strlen($value) > 0) ? true : false;
}
Posted: Wed Sep 28, 2005 11:05 pm
by John Cartwright
What I like to do in my applications have 3 claseses have 3 classes for the following:
a) class.validate.php (contains all the validation methods, such as isPostalCode, isAllLetters, whatever your needs may be) (this is a static class)
b) class.checkvalidate.php
I pass 2 things to this function, an array of expected values and validation type (see class.validate.php) and the input method ($_GET, $_POST, $_COOKIE, whatever. Although this does not need to be an actual input type, you can pass anything you need validated to this class.
c) class.erroroutput.php
This will be called during the checkvalidate process which will build the appropriate errors into an array. For example, it will sort all the "missing variables, and all the invalid variables
In the end it looks something along the lines of
Code: Select all
$valid = array('username' => 'isAllLetters', 'email' => 'isEmail');
$validation = new checkvalidate();
if ($validation->isValid($valid, $_POST)) {
$errors = $validation->getErrors();
}
else {
//everyone is valid..
}