PDA

Pogčedajte punu verziju : Jos jedna php klasica za validaciju forme


sinisake
26. 01. 2013., 22:42
Ima bolje i pametnije napisanih i sveobuhvatnijih, ali evo... mozda cak nekome i posluzi, za neke skromnije potrebe... :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
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

Br@nkoR
26. 01. 2013., 23:42
Prvo što primetih:

public function __construct()
{
foreach($_POST as $key=>$value) {
$_SESSION[$key]=$value;
}
}

Može se upisati bilo koja promenljiva u sesiju (npr. admin, logged, loggedin, user....)

sinisake
27. 01. 2013., 00:16
Eh, ostavio sam to zarad kreiranja session varijabli i ispisivanja u poljima forme, ali cu naci drugi nacin! Hvala ;)

webarto
27. 01. 2013., 00:19
Previše ti radi ova metoda, u suštini, ovo je funkcija unutar class :) Razloži na proste faktore.

sinisake
27. 01. 2013., 01:13
Da, oseti se taj amaterski OOP smek. :D
Mozda bi upotreba klase (oop-a) imala smisla ukoliko bih ovo pretvorio u kompletan paket - kreiranje i validaciju forme (pa mozda i slanje maila)...
To sam uradio svojevremeno, ali je kod toliko prljav da ga ne bih postavljao. :)

webarto
27. 01. 2013., 01:18
Ne, ne, treba da samo za validaciju služi, nisam mislio na to, već da razložiš filtere na metode, i onda odvojeno procesiraš... pogledaj kako je ovo urađeno: https://github.com/ircmaxell/filterus/tree/master/lib/Filterus

sinisake
27. 01. 2013., 01:42
Da, da, (mislim da:)) znam na sta si mislio, no dodao sam ono samo usput.
Da li bi to znacilo da se za svako polje/tip polja u formi poziva i razlicita metoda?

$validator->validate_email($_POST['email'])
$validator-> validate_text($_POST['name'],opcioni parametri)...

To sam zapravo zeleo da izbegnem (koliko je moguce!), da se u samoj 'pripremi validacije' mnogo kucka...

Mada, sad kad gledam... ovim bi se doslo na isto... ona 'konfiguracija' (onaj $vars array) u primeru isto oduzima vreme, a ovo je i znatno preglednije... :D

webarto
27. 01. 2013., 02:32
Napravi metodu za svaku operaciju, i onda napravi jednu "glavnu" metodu, tipa process(), u kojoj ćeš vršiti ove provjere.


$min = function ($var, $rules)
{
preg_match('%min=([0-9]{1,10})%', $rules, $matches);
if (empty($matches[1]))
return false;
return strlen($var) < (int)$matches[1] ? $matches[1] : true;
}
;

$var = 'php';
$rules = 'req|text|min=4';

if (strpos($rules, 'min=') !== false)
{
$num = $min($var, $rules);
if (is_numeric($num))
{
echo sprintf("Should have at least %d characters!", $num);
}
elseif ($num === false)
{
echo 'Invalid rule.';
}
}


Ne zadovoljava uslov: http://codepad.viper-7.com/GjvzpF
Pravilo ne valja: http://codepad.viper-7.com/fLY0k6

I stavljaj ovako...

$this->errors[] = $title . " should have at least $numb characters!";

A kasnije za prikaz...

echo implode('<br>', $this->errors);

I ctor promjeni u ovo...

public function __construct()
{
foreach ($_POST as $key => $value)
{
if ( ! isset($_SESSION[$key]))
{
$_SESSION[$key] = $value;
}
}
}

sinisake
27. 01. 2013., 12:02
'' i onda napravi jednu "glavnu" metodu, tipa process()''...

Hvala na konstruktivnoj kritici i pomoci, ali... ne znam kako to da izvedem. :D
Da preimenujemo temu u ''Jos jedna funkcija za validaciju forme"? :D

sinisake
27. 01. 2013., 13:45
U stvari... mozda bih i mogao. Hvala na ovom primeru, ce primenimo to... :)

webarto
27. 01. 2013., 15:32
:1073:

class Validator
{

public function process()
{
if (strpos($rules, 'min=') !== false)
{
$num = $this->min($var, $rules);
if (is_numeric($num))
{
$this->errors[] = "should have at least $num characters!";
} elseif ($num === false)
{
$this->errors[] = 'Invalid rule.';
}
}
}

private function min($var, $rules)
{
preg_match('%min=([0-9]{1,10})%', $rules, $matches);
if (empty($matches[1]))
return false;
return strlen($var) < (int)$matches[1] ? $matches[1] : true;
}

}

$validator = (new Validator($vars))->process();

Ovako nešto, nadam se da shvataš.

sinisake
27. 01. 2013., 16:00
Da, da, shvatio, cim uhvatim malo vise vremena stize poboljsana, skoro pa prava klasa. :)

sinisake
27. 01. 2013., 20:22
<?php

class Validator
{

var $errors=array();
var $output=array();



public function process($vars)
{

for($i=0;$i<count($vars);$i++)

{

$title=$vars[$i][0];
$rules=$vars[$i][1];
$var=$vars[$i][2];


//check required field
if(strpos($rules, 'req') !== false)
{

if($this->required($var))



{
$this->errors[] = $title." is required field!";

}


}

//only text is allowed

if(strpos($rules,'text')!==FALSE)

{
if($this->only_text($var))
{
$this->errors[]= $title. ' field should contain only letters!<br />';

}

}




//check minimal number of chars
if (strpos($rules, 'min=') !== false)
{
$num = $this->min($var, $rules);
if (is_numeric($num))
{
$this->errors[] = $title." should have at least $num characters!";
} elseif ($num === false)
{
$this->errors[] = 'Invalid rule.';
}
}

//check max number of chars
if (strpos($rules, 'max=') !== false)
{
$num = $this->max($var, $rules);
if (is_numeric($num))
{
$this->errors[] = $title." should have at most $num characters!";
} elseif ($num === false)
{
$this->errors[] = 'Invalid rule.';
}
}

//check email

if(strpos($rules,'valid_email')!==FALSE)

{

if($this->valid_email($var))
{
$this->errors[]= $title. ' is not a valid email address!<br />';
}


}

if(!is_array($var)) {
$this->output[]=$title. ' : '. $var. '<br />';
}
else
{
$this->output[]=$title. ' : '. implode(',',$var). '<br />';
}
}






if(!empty($this->errors))

{
return false;

}

else
{
return true;
}



}

//required field
private function required($var)
{


if(empty($var))
{
return true;

}






}
//only text

private function only_text($var)
{
if(preg_match('%[^A-Za-z ]%',$var))
return true;



}

//valid email

private function valid_email($var)
{
if(!filter_var($var, FILTER_VALIDATE_EMAIL))
{

return true;
}



}

//min number of chars
private function min($var, $rules)
{
preg_match('%min=([0-9]{1,10})%', $rules, $match);
if (empty($match[1]))
return false;
return strlen($var) < (int)$match[1] ? $match[1] : true;
}
//max number of chars

private function max($var, $rules)
{
preg_match('%max=([0-9]{1,10})%', $rules, $match);
if (empty($match[1]))
return false;
return strlen($var) > (int)$match[1] ? $match[1] : true;

}



}
//$validator = (new Validator($vars))->process();
?>





E, samo da pitam, pre nego sto nastavim (ili odustanem:D) ovako bi to trebalo, ili da se ne zakopavam dalje? :didntdoit

webarto
27. 01. 2013., 22:53
Jeste, tako nešto, barem bi ja tako u ovom tvom slučaju...

Ne koristi var, to je iz PHP4... stavi public/private/protected, ova 2 zadnja su u suštini ista, ako ćeš private, onda stavi i protected.

Ovo...
private function required($var)
{
if (empty($var))
{
return true;
}
}
To...
private function required($var)
{
return empty($var);
}

I formatiraj code, katastrofa je http://beta.phpformatter.com/

sinisake
28. 01. 2013., 12:21
I, evo, zahvaljujuci nesebicnoj webartovoj pomoci, poboljsane verzije:

<?php
class Validator
{
public function __construct($prefix)
{

foreach ($_POST as $key=>$value)
{

if(strpos($key,$prefix)!==false)
{
$_SESSION[$key]=$value;
}

}

}
public $errors = array( );
public $output = array( );
public function process( $vars )
{
for ( $i = 0; $i < count( $vars ); $i++ )
{
$title = $vars[ $i ][ 0 ];
$rules = $vars[ $i ][ 1 ];
$var = $vars[ $i ][ 2 ];
//check required field
if ( strpos( $rules, 'req' ) !== false )
{
if ( $this->required( $var ) )
{
$this->errors[] = $title . " is required field!";
}
}
//only text is allowed
if ( strpos( $rules, 'text' ) !== FALSE )
{
if ( $this->only_text( $var ) )
{
$this->errors[] = $title . ' field should contain only letters!';
}
}
//only numbers are allowed
if ( strpos( $rules, 'num' ) !== FALSE )
{
if ( $this->only_numbers( $var ) )
{
$this->errors[] = $title . ' field should contain only numbers!';
}
}
//check minimal number of chars
if ( strpos( $rules, 'min=' ) !== false )
{
$num = $this->min( $var, $rules );
if ( is_numeric( $num ) )
{
$this->errors[] = $title . " should have at least $num characters!";
}
elseif ( $num === false )
{
$this->errors[] = 'Invalid rule.';
}
}
//check max number of chars
if ( strpos( $rules, 'max=' ) !== false )
{
$num = $this->max( $var, $rules );
if ( is_numeric( $num ) )
{
$this->errors[] = $title . " should have at most $num characters!";
}
elseif ( $num === false )
{
$this->errors[] = 'Invalid rule.';
}
}
//check email
if ( strpos( $rules, 'valid_email' ) !== FALSE )
{
if ( $this->valid_email( $var ) )
{
$this->errors[] = $title . ' is not a valid email address!';
}
}
//check single checkbox
if ( strpos( $rules, 'type:check_single' ) !== FALSE )
{
if ( $this->single_checkbox( $var, $rules ) )
{
$this->errors[] = $title . " wrong entry!";
}
}
//check checkbox group
if ( strpos( $rules, 'type:check_multi' ) !== FALSE )
{
if ( $this->multi_checkbox( $var, $rules ) )
{
$this->errors[] = $title . " wrong entry!";
}
}
//check radio buttons group
if ( strpos( $rules, 'type:radio' ) !== FALSE )
{
if ( $this->radio_group( $var, $rules ) )
{
$this->errors[] = $title . " wrong entry!";
}
}
//only letters & numbers are allowed
if ( strpos( $rules, 'alpha_digit' ) !== FALSE )
{
if ( $this->alpha_digit( $var ) )
{
$this->errors[] = $title . ' field should contain only letters and/or numbers!<br />';
}
}
//custom chars
if ( strpos( $rules, 'custom' ) !== FALSE )
{
if ( $this->custom( $var, $rules ) )
{
$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 ( !empty( $this->errors ) )
{
return false;
}
else
{
return true;
}
}
//required field
private function required( $var )
{
return empty( $var );
}
//only text
private function only_text( $var )
{
if ( preg_match( '%[^A-Za-z ]%', $var ) )
return true;
}
//only numbers
private function only_numbers( $var )
{
if ( preg_match( '%[^0-9. ]%', $var ) )
return true;
}
// letters and numbers allowed
private function alpha_digit( $var )
{
if ( preg_match( '%[^A-Za-z0-9 ]%', $var ) )
return true;
}
//valid email
private function valid_email( $var )
{
if ( !filter_var( $var, FILTER_VALIDATE_EMAIL ) )
{
return true;
}
}
//min number of chars
private function min( $var, $rules )
{
preg_match( '%min=([0-9]{1,10})%', $rules, $match );
if ( empty( $match[ 1 ] ) )
return false;
return strlen( $var ) < (int) $match[ 1 ] ? $match[ 1 ] : true;
}
//max number of chars
private function max( $var, $rules )
{
preg_match( '%max=([0-9]{1,10})%', $rules, $match );
if ( empty( $match[ 1 ] ) )
return false;
return strlen( $var ) > (int) $match[ 1 ] ? $match[ 1 ] : true;
}
//check checkbox value
public function single_checkbox( $var, $rules )
{
preg_match( '%value:[0-9A-Za-z]{1,20}%', $rules, $match );
$value = str_replace( 'value:', '', $match[ 0 ] );
if ( !empty( $var ) )
if ( $var != $value )
{
return true;
}
}
//check checkboxes group value
private function multi_checkbox( $var, $rules )
{
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 ) )
return true;
}
}
//check radio group values
private function radio_group( $var, $rules )
{
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 ) )
return true;
}
//check custom
private function custom( $var, $rules )
{
if ( preg_match( '%\[.+\]%', $rules, $match ) )
{
$rule = $match[ 0 ];
}
if ( preg_match( "%" . $rule . "%", $var ) )
return true;
}
}
?>











upotreba i hm... dokumentacija :D


<?php
error_reporting(0);
session_start();
$prefix='frm_';
include('validator.php');
$validator= new Validator($prefix);

?>
<!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="frm_name" type="text" value="<?php echo $_SESSION["frm_name"]; ?>" />
<br />
Please enter your email: <br />
<input name="frm_email" type="text" value="<?php echo $_SESSION["frm_email"]; ?>" />
<br />
Please enter some number: <br />
<input name="frm_number" type="text" value="<?php echo $_SESSION["frm_number"]; ?>" />
<br />
I agree with terms and conditions:
<input name="frm_terms" type="checkbox" value="1" <?php if($_SESSION['frm_terms']=='1') echo 'checked' ?> />
<br />
Vehicle:<br />
<input type="checkbox" name="frm_vehicle[]" value="Bike" <?php if(in_array('Bike',$_SESSION["frm_vehicle"])) echo 'checked'; ?> >I have a bike<br>
<input type="checkbox" name="frm_vehicle[]" value="Car" <?php if(in_array('Car',$_SESSION["frm_vehicle"])) echo 'checked'; ?> >I have a car<br>
<input type="checkbox" name="frm_vehicle[]" value="Plane"<?php if(in_array('Plane',$_SESSION["frm_vehicle"])) echo 'checked'; ?> >I have a plane<br>
<br />
Gender:<br />
<input type="radio" name="frm_gender" value="male" <?php if($_SESSION['frm_gender']=='male') echo 'checked' ?> >Male<br />
<input type="radio" name="frm_gender" value="female"<?php if($_SESSION['frm_gender']=='female') echo 'checked' ?> >Female<br />
<br />
How did you hear about us: <br />
<select name="frm_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="frm_numbtext" type="text" value="<?php echo $_SESSION['frm_numbtext']; ?>" />
<br />
Message:<br />
<textarea name="frm_message" cols="" rows="" style="width:250px;height:130px;"><?php echo $_SESSION['frm_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['frm_name']),
array("Email", 'valid_email' , $_POST['frm_email']),
array("Test Number", 'req|num|max=4' , $_POST['frm_number']),
//single checkbox setup -> additional fields: type, checked value
array("Terms and Conditions", 'req|type:check_single|value:1' , $_POST['frm_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['frm_vehicle']),
// Radio button group setup -> additional fields in rules section: type, checked values
array("Gender", 'req|type:radio|values:(male,female)' , $_POST['frm_gender']),
// select dropdown setup
array("How did you hear about us", 'req|text' , $_POST['frm_how']),
//letters and text validation
array("Numbers and text", 'req|alpha_digit' , $_POST['frm_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['frm_message'])


);



if(!$validator->process($vars))
{
foreach ($validator->errors as $error)
{
echo $error.'<br />';

}

}
else

{
foreach ($validator->output as $line)
{
echo $line;

}
}


}

?>
</body>
</html>


Uskoro - jos suvisnih klasa. :1045:
Samo, moracu da smislim nesto malo egzoticnije i koliko-toliko korisnije, kao predmet klase.
Da, hvala na ovom linku za bjutifajer... jes' ga ulepsao, skoro ko pravi koder da je pis'o... :1016:

xippi
30. 01. 2013., 11:35
mislim da bi bilo kul da se ovakve stvari kace i na github ili tako negde kako bi mogle da se stalno apdejtaju poslednjim verzijama. takodje su vece sanse da se neko ukaci ako mu se projekat ili gist svidi i sam posalje komentar ili ispravku

mangia
30. 01. 2013., 16:35
Ja za popunjavanje formi, volim koristiti jquery i populate

npr

$('#nekaTamoForma').populate(<?php echo $blabla; ?>);

Gdje je $blabla formiran u kontroleru

$outputJSON = array(
"polje1" => $bla,
"polje2" => $b,
"polje3" => number_format($bla['tutu'], 2, '.', ''),
"polje4" => stripslashes($bla['huha']),
"polje5" => stripslashes($bla['josnesto']),
"polje6" => stripslashes($bla['nesto'])
);

$blabla = json_encode($outputJSON);

Tako ne petljam php tagove u view-u i dizajneri mogu da ga štemaju koliko hoće bez da paze na php kod.

sinisake
30. 01. 2013., 22:57
Lepo, nisam znao za taj plugin.