我過去做過的方式是爲它構建對象...表單對象,表單字段對象和表單字段驗證器對象。
所以你創建你的所有字段對象,如有必要,請安裝驗證它們,那麼一大堆附加到形式 - 所以你的東西,如排序結束:
$oFieldUsername = new FormField('username', new Validator(Validator::TYPE_EMAIL));
$oFieldPassword = new FormField('password', new Validator(Validator::TYPE_PASSWORD));
$oForm = new Form(Form::METHOD_POST, '/path/to/action.php');
$oForm->attachField($oFieldUsername);
$oForm->attachField($oFieldPassword);
//form has not been posted
if(!$oForm->isReceived()) {
$oForm->render('/path/to/view.tpl.php');
}
//the form HAS been posted but IS NOT VALID
elseif(!$oForm->isValid()) {
$oForm->render('/path/to/view.tpl.php');
}
//the form HAS been posted and the data LOOKS valid
else {
//do processing and hand-off
}
的驗證器處理諸如確定字段數據是否是必需的,如果數據匹配空字符串(RegExp),那麼它不是必需的。
但他們也可以處理電子郵件驗證(帶或不帶getmxrr()查找)或其他任何東西,你只是建立驗證類型特定的情況下...或者你有通用校驗:
new Validator(Validator::TYPE_EMAIL); //basic email validator
new Validator(Validator::TYPE_EMAIL_WITH_MX); //email validator with getmxrr()
new Validator(Validator::TYPE_REGEXP, '/^[\w]+$/'); //generic regular expression with the pattern to match as the second parameter
new Validator(Validator::TYPE_INT_MIN, 10); //integer with a minimum value of 10
new Validator(Validator::TYPE_REGEXP, '/^[\w\s]*$/', true); //the third parameter could be an override so that the validation is optional - if the field has a value it MUST validate, if it doesn't have a value, it's fine
這爲您提供儘可能多的靈活性,因爲您需要驗證。所有的Form::isValid()
方法都是循環遍歷所有附加的字段,檢查它們是否有Validator,如果是,Validator::isValid()
方法是否返回true。
你也可以添加多個校驗來場的東西,如:
//the field value must be an integer between 5 and 10 (inclusive)
$oField->addValidator(new Validator(Validator::TYPE_INT_MIN, 5));
$oField->addValidator(new Validator(Validator::TYPE_INT_MAX, 10));
......這就是我反正已經做了。
你可以檢查form_validation庫來了解CI是如何做到的 – 2012-04-26 10:24:03
Codeigniter有代碼來做到這一點,我不太確定你期望在「php native」中找到什麼。在PHP中沒有任何表單(您可以創建一個生成HTML表單的php文件,但沒有表示表單afaik的本機對象)。 – Nanne 2012-04-26 10:28:47
查看Quickform2 - IMHO是PHP表單最好的方法之一。 http://pear.php.net/package/HTML_QuickForm2 – ExternalUse 2012-04-26 10:32:01