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)
Explicit site key override. Optional — pulled from config by default. Default: from config.
withId(string)
Widget element ID. Default: 'g-recaptcha-{uniqid}'.
withTheme(RecaptchaV2Theme)
Light or Dark. Default: Light.
withType(RecaptchaV2Type)
Image or Audio. Default: Image.
withSize(RecaptchaV2Size)
Normal, Compact, or Invisible. Default: Normal.
withJsApiUrl(string)
Custom JS API URL. Default: Google CDN.
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)
Override the hidden input name. Default: auto-derived from form model as FormName[attribute].
->inputId(?string)
Override the hidden input ID. Default: auto-generated unique ID.

Container (inherited from BaseField)

->containerTag(string)
Wrapper tag. Default: 'div'.
->containerClass(string ...)
Wrapper CSS class(es). Default: 'mb-3'.
->useContainer(bool)
Enable/disable wrapper. Default: true.
->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
Error message (translatable). Default: 'The CAPTCHA verification failed.'.
secret
Custom secret (uses config default if null). Default: null.
sendRemoteIp
Whether to include the user's IP in verification. Default: false.