Skip to content

Instantly share code, notes, and snippets.

@phunehehe
Last active December 30, 2015 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phunehehe/7786796 to your computer and use it in GitHub Desktop.
Save phunehehe/7786796 to your computer and use it in GitHub Desktop.
Antispam for Yii form
<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>
<?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