sinisake |
26. 01. 2013. 23:42 |
Jos jedna php klasica za validaciju forme
Ima bolje i pametnije napisanih i sveobuhvatnijih, ali evo... mozda cak nekome i posluzi, za neke skromnije potrebe... :D
PHP kôd:
class Form_validator
{ var $errors=''; var $output=''; public function __construct() { foreach($_POST as $key=>$value) { $_SESSION[$key]=$value; } }
public function validate($vars)
{ for($i=0;$i<count($vars);$i++) { $title=$vars[$i][0]; $rules=$vars[$i][1]; $var=$vars[$i][2]; //check rules //required field if(strpos($rules,'req')!==FALSE) { if(empty($var)) $this->errors.= $title. ' is required field!<br />'; } //only text is allowed if(strpos($rules,'text')!==FALSE) { if(preg_match('%[^A-Za-z ]%',$var)) $this->errors.= $title. ' field should contain only letters!<br />'; } //only letters & numbers are allowed if(strpos($rules,'alpha_digit')!==FALSE) { if(preg_match('%[^A-Za-z0-9 ]%',$var)) $this->errors.= $title. ' field should contain only letters and/or numbers!<br />'; } //valid email if(strpos($rules,'valid_email')!==FALSE) { if(!filter_var($var, FILTER_VALIDATE_EMAIL)) { $this->errors.= $title. ' is not a valid email address!<br />'; }
} //only numeric chars if(strpos($rules,'num')!==FALSE) { if(preg_match('%[^0-9. ]%',$var)) $this->errors.= $title. ' field should contain only numbers!<br />'; } //minimal chars if(strpos($rules,'min=')!==FALSE) { if(preg_match('%min=[0-9]{1,10}%',$rules,$match)) { $numb=str_replace('min=','',$match[0]); } if(!empty($var)) if(strlen($var)<$numb) $this->errors.= $title. " should have at least $numb characters!<br />"; } //max chars if(strpos($rules,'max=')!==FALSE) { if(preg_match('%max=[0-9]{1,10}%',$rules,$match)) { $numb=str_replace('max=','',$match[0]); } if(!empty($var)) if(strlen($var)>$numb) $this->errors.= $title. " should have at most $numb characters!<br />"; } //check single checkbox if(strpos($rules,'type:check_single')!==FALSE) { if(preg_match('%value:[0-9A-Za-z]{1,20}%',$rules,$match)) { $value=str_replace('value:','',$match[0]); } if(!empty($var)) if($var!=$value) $this->errors.= $title. " wrong entry!<br />"; } //check checkbox group/multiple checkboxes if(strpos($rules,'type:check_multi')!==FALSE) { if(preg_match('%values:[()0-9A-Za-z,]{1,200}%',$rules,$match)) { $replace=array('values:','(',')'); $values=str_replace($replace,'',$match[0]); $values_array=explode(',',$values); } if(!empty($var)) foreach ($var as $val) { if(!in_array($val,$values_array)) $this->errors.= $title. " wrong entry!<br />"; } } //check radio buttons group if(strpos($rules,'type:radio')!==FALSE) { if(preg_match('%values:[()0-9A-Za-z,]{1,200}%',$rules,$match)) { $replace=array('values:','(',')'); $values=str_replace($replace,'',$match[0]); $values_array=explode(',',$values); } if(!empty($var)) if(!in_array($var,$values_array)) $this->errors.= $title. " wrong entry!<br />"; } //only numeric chars if(strpos($rules,'custom')!==FALSE) { if(preg_match('%\[.+\]%',$rules,$match)) { $rule=$match[0]; } if(preg_match("%".$rule."%",$var)) $this->errors.= $title. " contains disallowed char(s)!<br />"; } if(!is_array($var)) { $this->output.=$title. ' : '. $var. '<br />'; } else { $this->output.=$title. ' : '. implode(',',$var). '<br />'; } } if($this->errors!='') { return false; } else { return true; } } }
Upotreba:
PHP kôd:
<?php error_reporting(0); session_start(); include('form_validator.php'); $validator= new Form_validator; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head>
<body> <form action="" method="post"> Please enter your name: <br /> <input name="name" type="text" value="<?php echo $_SESSION['name']; ?>" /> <br /> Please enter your email: <br /> <input name="email" type="text" value="<?php echo $_SESSION['email']; ?>" /> <br /> Please enter some number: <br /> <input name="number" type="text" value="<?php echo $_SESSION['number']; ?>" /> <br /> I agree with terms and conditions: <input name="terms" type="checkbox" value="1" <?php if($_SESSION['terms']=='1') echo 'checked' ?> /> <br /> Vehicle:<br /> <input type="checkbox" name="vehicle[]" value="Bike" <?php if(in_array('Bike',$_SESSION['vehicle'])) echo 'checked'; ?> >I have a bike<br> <input type="checkbox" name="vehicle[]" value="Car" <?php if(in_array('Car',$_SESSION['vehicle'])) echo 'checked'; ?> >I have a car<br> <input type="checkbox" name="vehicle[]" value="Plane"<?php if(in_array('Plane',$_SESSION['vehicle'])) echo 'checked'; ?> >I have a plane<br> <br /> Gender:<br /> <input type="radio" name="gender" value="male" <?php if($_SESSION['gender']=='male') echo 'checked' ?> >Male<br /> <input type="radio" name="gender" value="female"<?php if($_SESSION['gender']=='female') echo 'checked' ?> >Female<br /> <br /> How did you hear about us: <br /> <select name="how"> <option value="0">Please select one option</option> <option value="Google">Google</option> <option value="Radio">Radio</option> <option value="TV">TV</option> <option value="Other">Other</option> </select> <br /> Numbers and text:<br /> <input name="numbtext" type="text" value="<?php echo $_SESSION['numbtext']; ?>" /> <br /> Message:<br /> <textarea name="message" cols="" rows="" style="width:250px;height:130px;"><?php echo $_SESSION['message']; ?></textarea> <br /><br /> <input name="submit" type="submit" value="Submit" /> </form> <?php
if(isset($_POST['submit']))
{
// Set variable description titles (used for error messages), names, and validation rules + type of fields (checkboxes and radio buttons). /* req=required field text=only letters are allowed min = minimal number of characters max = maximal number of characters valid_email = obviously... :) num = only numeric chars alpha_digit = numbers&letters allowed custom = format:[^your custom list of allowed characters in field]
types: check_single - single check box check_multi - checkbox group radio - radio buttons group
//rules for check box -> check_single -> one checkbox, value:-> check for exact value! check_multi -> checkbox group values:-> check for exact values!
*/ $vars = array ( array("Name", 'req|text|min=6|max=20' , $_POST['name']), array("Email", 'valid_email' , $_POST['email']), array("Test Number", 'req|num|max=4' , $_POST['number']), //single checkbox setup -> additional fields: type, checked value array("Terms and Conditions", 'req|type:check_single|value:1' , $_POST['terms']), //single checkbox setup -> additional fields in rules section: type, multiple checkboxes, checked values array("Vehicle", 'req|type:check_multi|values:(Bike,Car,Plane)' , $_POST['vehicle']), // Radio button group setup -> additional fields in rules section: type, checked values array("Gender", 'req|type:radio|values:(male,female)' , $_POST['gender']), // select dropdown setup array("How did you hear about us", 'req' , $_POST['how']), //letters and text validation array("Numbers and text", 'req|alpha_digit' , $_POST['numbtext']),
//custom regex setup -> add custom ALLOWED characters, if variable contains any other chars - validation will fail -> format: [^custom chars] array("Message", 'req|custom[^A-Za-z0-9-,.\r\n!?= ]' , $_POST['message'])
);
//if validation fails print error messages if(!$validator->validate($vars)) {
echo $validator->errors; } //else send mail, or whatever... else { echo 'Validation passed!<br />'; echo $validator->output; }
}
?> </body> </html>
Naravno, ovo je vise vezbica, kritike samog koncepta i razrade su dobrodosle. :D
|