Just a function I've been using lately in both PHP and Javascript form in order to quickly validate data handed in by a user via form post. Wanted to see what some others thought of the concept and implementation. Thanks 🙂
function validate_field( $variable , $nullable = false , $regex = null , $redirect = false , $redirect_target = null )
{
if ( !$nullable && ( $variable == null || $variable == "" ) )
{
// Validation Failed
if ( $redirect )
{
redirect($redirect_target.'1');
exit();
}
else
{
return false;
}
}
if ( $nullable && ( $variable == null || $variable == "" ) )
{
return $variable;
}
if ( $regex != '' && $regex != null )
{
if ( !preg_match($regex, $variable) )
{
// Validation Failed
if ( $redirect )
{
redirect($redirect_target.'2');
exit();
}
else
{
return false;
}
}
}
return $variable;
}