Skip to content

Precognition ​

Precognition validates a form against the server's own rules before it's sent, so you don't repeat them in the browser. The server needs Precognition support on that route: it validates the request and answers without saving anything.

With useForm ​

Pass a method and URL first:

gts
form = useForm('put', `/posts/${this.args.props.post.id}`, { title: '' }).setValidationTimeout(300);

<template>
  <input {{bind this.form 'title' validate=true}} />
  {{! validates on change; validate='blur' for another event }}
  {{#if this.form.validating}}Checking…{{/if}}
  {{#if (this.form.valid 'title')}}✓{{/if}}
  {{#if this.form.errors.title}}<p>{{this.form.errors.title}}</p>{{/if}}
</template>

form.validate('title') checks one field and form.validate() the touched ones. With {{on "change" (fn form.validate "title")}} the event argument is ignored. Only fields that were touched show errors.

There are also touch, touched, valid, invalid, validating, validator(), validateFiles, withoutFileValidation, withAllErrors, setErrors and forgetError. form.submit() sends to the same method and URL. A validation still waiting out its debounce is dropped when the form is sent.

The demo's Edit page works this way. See its source, or try it ↗ .

With <Form> ​

<Form> validates against its own @action:

gts
<Form @action='/posts' @method='post' as |form|>
  <input name='email' {{on 'change' (fn form.validate 'email')}} />
  {{#if (form.valid 'email')}}✓{{/if}}
</Form>

On the server ​

In the demo, a failed validation answers 422 before the handler runs. When it passes, the handler sees the Precognition header and answers 204 instead of saving. A small middleware on those routes keeps only the errors of the fields the browser asked about:

rs
//! Precognition: the browser asks whether a form would pass validation without sending it for real.
//!
//! The client marks those requests with `Precognition: true` and, while the user is still filling the form in,
//! names the fields it cares about in `Precognition-Validate-Only`. A handler checks `requested` right after its
//! `Valid<T>` argument has passed and answers `passed()` instead of saving. When validation fails, Laravel has
//! already answered with a 422 before the handler runs; this middleware keeps only the errors of the named fields,
//! so the user isn't told about fields they haven't reached yet, and marks every answer as a Precognition one.

use laravel::axum::body::{Body, to_bytes};
use laravel::axum::http::{self, HeaderMap, HeaderValue, StatusCode, header};
use laravel::http::{IntoResponse, Next, middleware};
use laravel::prelude::*;
use serde_json::{Value, json};

/// Whether the request only asks to validate.
pub fn requested(headers: &HeaderMap) -> bool {
    headers.get("precognition").is_some_and(|value| value == "true")
}

/// The answer for input that passed validation.
pub fn passed() -> Response {
    (
        StatusCode::NO_CONTENT,
        [
            ("precognition", "true"),
            ("precognition-success", "true"),
            ("vary", "Precognition"),
        ],
    )
        .into_response()
}

#[middleware]
pub async fn precognitive(request: Request, next: Next) -> Response {
    if !requested(request.headers()) {
        return next.run(request).await;
    }

    let only: Option<Vec<String>> = request.header("precognition-validate-only").map(|fields| {
        fields
            .split(',')
            .map(str::trim)
            .filter(|field| !field.is_empty())
            .map(str::to_owned)
            .collect()
    });

    let response = next.run(request).await;

    let mut response = match only {
        Some(only) if response.status() == StatusCode::UNPROCESSABLE_ENTITY => keep_errors(response, &only).await,
        _ => response,
    };

    let headers = response.headers_mut();
    headers.insert("precognition", HeaderValue::from_static("true"));
    headers.insert(header::VARY, HeaderValue::from_static("Precognition"));
    response
}

/// Drops the errors of fields outside `only` (a field also covers its nested keys, `items` covers `items.0`).
async fn keep_errors(response: Response, only: &[String]) -> Response {
    let (parts, body) = response.into_http().into_parts();

    let Ok(bytes) = to_bytes(body, 1024 * 1024).await else {
        return Response::from_http(http::Response::from_parts(parts, Body::empty()));
    };

    let Ok(mut payload) = serde_json::from_slice::<Value>(&bytes) else {
        return Response::from_http(http::Response::from_parts(parts, Body::from(bytes)));
    };

    let covers = |key: &str| {
        only.iter().any(|field| {
            key == field
                || key
                    .strip_prefix(field.as_str())
                    .is_some_and(|rest| rest.starts_with('.'))
        })
    };

    let Some(errors) = payload.get_mut("errors").and_then(Value::as_object_mut) else {
        return Response::from_http(http::Response::from_parts(parts, Body::from(bytes)));
    };

    errors.retain(|key, _| covers(key));

    if errors.is_empty() {
        return passed();
    }

    let first = errors
        .values()
        .next()
        .and_then(|messages| messages.get(0))
        .and_then(Value::as_str)
        .unwrap_or_default();
    let message = json!(first);
    payload["message"] = message;

    let mut parts = parts;
    parts.headers.remove(header::CONTENT_LENGTH);
    Response::from_http(http::Response::from_parts(parts, Body::from(payload.to_string())))
}

Released under the MIT License.