reCAPTCHA

reCAPTCHA

Google reCAPTCHA v2 & v3 fields & validation

v2

Field

use YiiRocks\Recaptcha\RecaptchaV2Field;
use YiiRocks\Recaptcha\RecaptchaV2Theme;
use YiiRocks\Recaptcha\RecaptchaV2Size;
use YiiRocks\Recaptcha\RecaptchaV2Type;

echo RecaptchaV2Field::field($form, 'captcha')
    ->withTheme(RecaptchaV2Theme::Dark)
    ->withSize(RecaptchaV2Size::Compact)
    ->withType(RecaptchaV2Type::Audio)
    ->withId('my-captcha')
    ->withCallback('onSuccess')
    ->render();

Options

withSiteKey(string)
from config
Explicit site key override. Optional - pulled from config by default.
withId(string)
'g-recaptcha-{uniqid}'
Widget element ID.
withTheme(RecaptchaV2Theme)
themeV2 param, else Light
Light or Dark. Overrides the app-wide themeV2 default for this field.
withType(RecaptchaV2Type)
typeV2 param, else Image
Image or Audio. Overrides the app-wide typeV2 default for this field.
withSize(RecaptchaV2Size)
sizeV2 param, else Normal
Normal, Compact, or Invisible. Overrides the app-wide sizeV2 default for this field.
withJsApiUrl(string)
Google CDN
Custom JS API URL.
withCallback(string)
JavaScript callback function name on successful verification.
withExpiredCallback(string)
JavaScript callback function name when the CAPTCHA expires.
withErrorCallback(string)
JavaScript callback function name when an error occurs.

Inherited from InputField

->name(string)
auto-derived from form model as FormName[attribute]
Override the hidden input name.
->inputId(?string)
auto-generated unique ID
Override the hidden input ID.

Container (inherited from BaseField)

->containerTag(string)
'div'
Wrapper tag.
->containerClass(string ...)
'mb-3'
Wrapper CSS class(es).
->useContainer(bool)
true
Enable/disable wrapper.
->containerAttributes(array)
Set all wrapper attributes.
->addContainerAttributes(array)
Merge additional wrapper attributes.

Validation

Use the attribute on your form model property:

use YiiRocks\Recaptcha\RecaptchaV2Rule;

final class ContactForm
{
    #[RecaptchaV2Rule(sendRemoteIp: true)]
    public string $gRecaptchaResponse = '';
}

Rule parameters

message
'The CAPTCHA verification failed.'
Error message (translatable).
secret
null
Custom secret (uses config default if null).
sendRemoteIp
false
Whether to include the user's IP in verification.