用PHP在页面顶部显示验证错误


Showing validation errors at top of page with PHP

我已经编写了一个Form对象(代码:http://pastebin.com/U1xMRhdn)验证在表单字段中输入的信息是否有效。一个例子:

<?php
$f = Form(...);
//I would like to output the amount of errors up here.
$f->textBox(...);
$f->radioArea(...);
if($f->getErrors()>0)
    echo "You have "+$f->getErrors();+" errors, go back and try again";
?>

如果用户没有在文本框中输入任何内容,则错误计数器将递增。问题是:我想在页面顶部显示用户出错的次数。但是,当我尝试执行此操作时,错误计数器检索到0个错误,因为这些项尚未在函数textBoxradioArea中进行验证。有没有办法在脚本末尾捕获一个值并将其返回到脚本顶部?还是我必须找到另一种计算错误的方法?

您是否考虑过使用输出缓冲区

像这样:

<?php
ob_start(); // start buffering
$f = Form(...);
//I would like to output the amount of errors up here.
$f->textBox(...);
$f->radioArea(...);
$form_html = ob_get_clean(); // end the buffer, get it, and clean it
if($f->getErrors()>0)
    echo "You have "+$f->getErrors();+" errors, go back and try again";
echo $form_html;
?>

使用get-data-req并将答案吐回ure选项的div。每次用户输入一些东西时,ajax将调用php(如果有错误),答案将被ajaxin。如果您希望每次在文本区域中按键都能运行验证,则可以使用on键