Last active
December 30, 2015 05:59
-
-
Save phunehehe/7786796 to your computer and use it in GitHub Desktop.
Antispam for Yii form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="antispam"> | |
<?= $form->textField($model, '_yii_antispam'); ?> | |
<?= $model->_yii_antispam_message ?> | |
<script type="text/javascript"> | |
$('.antispam').hide(); | |
$(".antispam input[name='<?= get_class($model) ?>[_yii_antispam]']").val('human'); | |
</script> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Prevent automated POST (actually non-GET) requests by checking a form | |
* attribute set by JavaScript, in the hope that spammers will not execute | |
* JavaScript. | |
* | |
* Usage: | |
* 1. Extend MyFormModel instead of CFormModel | |
* class ContactForm extends MyFormModel {} | |
* 2. If necessary, use `array_merge(parent::rules(), array(...))` when | |
* defining validation rules | |
* public function rules() { | |
* return array_merge(parent::rules(), array( | |
* // rules | |
* )); | |
* } | |
* 3. When rendering, include `_antispam` inside the form widget | |
* <?= $this->renderPartial('//shared/_antispam', array( | |
* 'form' => $form, | |
* 'model' => $model)) ?> | |
*/ | |
class MyFormModel extends CFormModel { | |
public $_yii_antispam; | |
public $_yii_antispam_message = 'Type "human" if you are not a robot.'; | |
public function rules() { | |
return array( | |
array( | |
'_yii_antispam', 'compare', | |
'compareValue' => 'human', | |
'message' => $this->_yii_antispam_message, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment