Created
June 6, 2012 01:40
-
-
Save benmay/2879338 to your computer and use it in GitHub Desktop.
Simple handy form validation functions used on a few diff forms.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
On Form Page: | |
$form_errors = process_form(); | |
In the form (contains any validation errors) | |
<?php validation_errors(); ?> | |
Form Elements (example) | |
<p> | |
<label>First Name *</label> | |
<input type="text" name="fname" <?php set_val('fname'); ?> /> | |
<?php form_error('fname');?> | |
</p> | |
/////////------------------------ | |
function process_form() | |
{ | |
if($_POST['username']==""): | |
$error=true; | |
$valdata['missing']['username']=true; | |
else: | |
if(username_exists($_POST['username'])): | |
$error=true; | |
$valdata['exists']['username']=true; | |
endif; | |
endif; | |
if($_POST['email']==""): | |
$error=true; | |
$valdata['missing']['email']=true; | |
else: | |
if(!is_email($_POST['email'])): | |
$error=true; | |
$valdata['invalidemail']['email']=true; | |
endif; | |
endif; | |
// Etc | |
if(isset($error)): | |
return $valdata; | |
endif; | |
// Else continue processing form | |
} | |
function validation_errors() | |
{ | |
global $form_errors; | |
if(isset($form_errors['error'])) | |
{ | |
foreach($form_errors['error'] as $error): | |
echo '<p><span style="color:red">Error: '.$error[0].'</span></p>'; | |
endforeach; | |
} | |
} | |
function form_error($name) | |
{ | |
global $form_errors; | |
if(isset($form_errors['missing'][$name])) | |
echo '<span style="color:red">This field is required</span> '; | |
if(isset($form_errors['invalidemail'][$name])) | |
echo '<span style="color:red">This is not a valid email address</span> '; | |
if(isset($form_errors['match'][$name])) | |
echo '<span style="color:red">This does not match</span> '; | |
if(isset($form_errors['exists'][$name])) | |
echo '<span style="color:red">This username already exists</span> '; | |
if(isset($form_errors['roarcap'][$name])) | |
echo '<span style="color:red">Sorry the captcha is incorrect. Try again </span> '; | |
} | |
function set_val($key,$returnextra=true) | |
{ | |
if(isset($_POST[$key]) && ($_POST[$key]!="")): | |
if($returnextra): | |
echo 'value="'.$_POST[$key].'"'; | |
else: | |
echo $_POST[$key]; | |
endif; | |
endif; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment