这些方面的东西可能会很好:
<?php
$validation = Array(
"field1" => Array( // "field1" is the name of the input field
"required" => true, // or false
"minlength" => 5, // use 0 for no minimum
"maxlength" => 10, // use 9999 (or other high number) for no maximum
"regex" => "^[a-zA-Z0-9]+$" // use empty string for no regex
),
"field2" => .......
....
);
if( $_POST) {
foreach($validation as $k=>$v) {
if( !isset($_POST[$k])) {
if( $v['required']) die("Field ".$k." is required");
}
else {
$l = strlen($_POST[$k]);
if( $l < $v['minlength']) die("Field ".$k." too short");
if( $l > $v['maxlength']) die("Field ".$k." too long");
if( !preg_match("(".$v['regex'].")",$_POST[$k])) die("Field ".$k." incorrect format");
}
}
// all ok!
}
?>
<script type="text/javascript">
(function(rules) {
var die = function(str) {alert(str); return false;};
document.getElementById('myForm').onsubmit = function() {
var elms = this.elements, i, it, r, s;
for( i in rules) {
r = rules[i];
it = elms.namedItem(i);
if( typeof it == "undefined") {
if( r.required) return die("Field "+i+" is required");
}
else {
s = it.length;
if( s < r.minlength) return die("Field "+i+" too short");
if( s > r.maxlength) return die("Field "+i+" too short");
if( !s.match(new RegExp(r.regex))) return die("Field "+i+" incorrect format");
}
}
return true;
};
})(<?=json_encode($validation)?>);
</script>
正如你所看到的,一般的想法是定义一组规则,然后神奇的发生在json_encode($validation)
- 这将规则传递到 JavaScript 环境中。您仍然必须复制验证代码以使其在 PHP 和 JS 中运行,但至少现在您可以添加更多规则,而无需在两个地方更改代码。希望这可以帮助!