I just stumbled upon a jQuery plugin called jquery-ahm. It moves the validation logic to the server, but executes it at the client with JavaScript. At the bottom of the page you see an example for form validation.
Html markup:
<form id="form" action="/a.form" method="post" class="ahm">
<p>Name</p>
<input name="name" id="name" value="" type="text">
<p>Email</p>
<input name="email" id="email" value="" type="text">
<p>Password</p>
<input name="password" id="password" value="" type="text">
<br><input value="Submit Form" type="submit">
</form>
PHP code:
<?php
// catch errors
foreach (array("name", "email", "password") as $key) {
if (empty($_POST[$key])) {
$error["#$key/addClass"] = "error";
$error["#$key/after"] = "<span class="error">Please enter $key</span>";
}
}
// get response
if (!empty($error)) {
$reset["input.error/removeClass"] = "error";
$reset["span.error/remove"] = "";
$response = $reset + $error; // reset errors before applying new ones
} else {
$response["#form/replaceWith"] = "<strong>Form successfully submitted</strong>";
}
// return response
return $response;
?>
Result:
