. , .
, , , ajax , javascript eval.
, $rulesPHP rulesJS . , - .
class Validation
{
protected static $rulesPHP =
array(
'positiveInteger' => array('($x === int($x))', '($x > 0)'),
'alphanumericString' => array(....)
);
protected static $rulesJS =
array(
'positiveInteger' => array('(x === int(x))', '(x > 0)'),
'alphanumericString' =>array(..... )
);
public static getValidatorPHP($type)
{
if (!isset($rulesPHP[$type])) return false;
$exp = explode(' && ', self::$rulesPHP[$type]);
return function($x) use ($exp)
{
return eval($exp);
};
}
public static getJsRules($type)
{
if (!isset($rulesJS[$type])) return false;
$exp = explode(' && ', self::$rulesJS[$type]);
return $exp;
}
}
:
$posIntValidator = Validation::getValidatorPHP('positiveInteger');
$posIntValidator($_POST['text1']);
Ajax ruleaccessor.php:
$t = $_GET['type'];
$out = Validation::getJsRules($t);
echo $out;
JavaScript:
function getValidator(type)
{
var rules;
$.get('/ruleaccessor.php?type=' + type, function(in) {rules = in;});
return function(x){return eval(rules);};
}
validatePosInt = getValidator('positiveInteger');
validatePosInt($('#text1').val());
, , , . , .
, , , - .