Validation

laravel-rust-captcha Alpha Laravel for Rust

The rule

use laravel_rust_captcha::Captcha;

#[validate(required, Captcha::session())]                 // PHP: 'required|captcha'
#[validate(required, Captcha::session().profile("contact"))]
#[validate(required, Captcha::keyed().profile("math"))]   // PHP: 'required|captcha_api:'.$key.',math'
#[validate(required, Captcha::keyed().key_field("key"))]
  • Without profile, the profile is default. A challenge issued for another profile fails, so an easier profile can't pass a stricter form. In PHP any challenge passed any form.
  • The rule is implicit: a missing or blank answer fails even without required. In PHP the rule passed an empty field unless required came first.
  • Session mode needs the route in the web middleware group. Without a session, the request fails with an error instead of a wrong-answer message.
  • With CAPTCHA_DISABLE=true, the rule passes, as in PHP.

Messages

The default message is "The :attribute is incorrect.". PHP showed the raw key validation.captcha. Give required its own message to tell a missing answer from a wrong one:

#[validate(
    required.message("Please enter the security code."),
    Captcha::session().profile("contact").message("The security code is incorrect."),
    label = "security code"
)]
captcha: String,

Checking by hand

use laravel_rust_captcha::{Verdict, check, check_keyed};

match check(&request, "contact", &answer).await? {
    Verdict::Passed => {}
    Verdict::Wrong { remaining } => { /* remaining: attempts left, None when unlimited */ }
    Verdict::Expired | Verdict::Missing | Verdict::Exhausted | Verdict::Throttled | _ => {}
}
let verdict = check_keyed(request.ip(), &key, "math", &answer).await?;
VerdictMeaning
PassedCorrect. This check used the challenge up; no other check can pass it.
Wrong { remaining }Wrong. Some(0) means the challenge is spent.
ExpiredPast the deadline.
MissingNo open challenge: never issued, used, replaced by a newer image, or gone after its deadline.
ProfileMismatchA keyed challenge of another profile. It is not used up.
ExhaustedThe attempt limit was reached before this check.
ThrottledToo many wrong answers from this client for this profile in the last minute.

An error (Err) means the store failed or timed out. The check fails closed: it never passes on an error. PHP's captcha_check and captcha_api_check returned true or false; verdict.passed() gives the same.