reCAPTCHA

reCAPTCHA

Google reCAPTCHA v2 & v3 fields & validation

v3

The token is fetched on form submit (not on page load), preventing unexpected challenge popups. The form is auto-resolved via closest("form") - no formId needed when the hidden input is inside the form.

use Yiisoft\FormModel\FormModel;
use YiiRocks\Recaptcha\RecaptchaV3Field;
use YiiRocks\Recaptcha\RecaptchaV3Badge;

echo RecaptchaV3Field::field($form, 'captcha')
    ->withAction('login')
    ->withFormId('login-form')
    ->withBadge(RecaptchaV3Badge::Hidden)
    ->render();
withSiteKey string
from config
Explicit site key override.
withAction string
''
Action name sent to Google (must match the rule's action if set).
withFormId string
Explicit form ID. When omitted the form is auto-resolved via closest("form").
withBadge RecaptchaV3Badge
badgeV3 param, else BottomRight
BottomRight, BottomLeft, or Hidden.
withJsApiUrl string
Google CDN
Custom JS API URL.
withTranslator ?TranslatorInterface
from registry
Translator for the hidden badge legal notice.
withExecuteTimeout ?int
5000 ms
Fallback form submission timeout (null = disabled).
->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.
->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.

Hidden badge: When Badge::Hidden is selected, the legal notice text (“This site is protected by reCAPTCHA…”) is displayed automatically and translated when a translator is available (either via withTranslator() or through RecaptchaRegistry).

Use the attribute on your form model property:

use YiiRocks\Recaptcha\RecaptchaV3Rule;

final class LoginForm
{
    #[RecaptchaV3Rule(
        threshold: 0.5,
        action: 'login',
        sendRemoteIp: true,
    )]
    public string $gRecaptchaResponse = '';
}

Important: If you set ->withAction('...') on the v3 field, you must also set action: '...' on the rule with the same value. If neither is set, no action is sent and the check is skipped entirely.

threshold float
0.5
Minimum score (0.0 - 1.0).
action ?string
null
Expected action name (skipped if null).
message string
'The CAPTCHA verification failed.'
Error message (translatable).
scoreTooLowMessage string
'The CAPTCHA score is too low.'
Error when score is below threshold.
actionMismatchMessage string
'The CAPTCHA action does not match.'
Error when action doesn't match.
secret ?string
null
Custom secret (uses config default if null).
sendRemoteIp bool
false
Whether to include the user's IP in verification.