Skip to content

Form validation — server errors on the right fields ​

A form submit in a LaravelUi5 app is a Ui5Action (LaravelUi5.call), never an OData write. When the server rejects the payload, the platform now places each validation error on the control that produced it — the field turns red with its message, and the full set is available to a MessagePopover — with no per-field wiring and no client-side validation schema. The single convention that makes this work: a control's binding path equals its Laravel validation key.

This note documents the whole chain (SDK → Core → host consumer) because the mechanism only reads correctly end-to-end. It is the pattern the Partners app uses across every form; new forms opt in with two lines.

The chain, back to front ​

1. Backend — the 422 contract (AbstractSdkFormRequest) ​

Ui5Actions are a JSON API surface, so a validation failure must be a 422 with the messages, not Laravel's default redirect-back-with-errors. The SDK base request enforces that (laravelui5/sdk, src/Http/Requests/AbstractSdkFormRequest.php):

php
protected function failedValidation(Validator $validator): void
{
    throw new HttpResponseException(response()->json([
        'status'  => 'Error',
        'message' => $validator->errors()->first(),   // the general summary
        'errors'  => $validator->errors()->toArray(), // { field: [msg, …] }
    ], 422));
}

errors is Laravel's native shape — a map of validation key → message array, including dotted keys for nested/tabular input (workers.0.rate). Nothing here is new machinery; it is the standard Laravel validation body, delivered as JSON.

Why the override exists. Without it, a failed FormRequest renders as a 302 redirect to /, which LaravelUi5.call follows transparently (redirect: "follow") — the caller sees an opaque success-shaped HTML response and the form silently does nothing. This was the original "Create Login does nothing" symptom that surfaced the whole mechanism. Any FormRequest behind a Ui5Action must extend AbstractSdkFormRequest so failedValidation answers 422 JSON.

2. Transport — the error reaches the caller (Connection) ​

Core's client library already carried the body to the caller. On a non-OK response, Connection.handleJsonResponse (ui5-core-lib) throws an Error with the parsed payload attached:

js
if (!response.ok) {
    const error = new Error(response.statusText);
    error.status = response.status;   // 422
    error.cause  = payload;           // { status, message, errors }
    throw error;
}

So the field errors are err.cause.errors and the general summary is err.cause.message. This layer stays pure transport — it does not touch the UI.

3. The seam — LaravelUi5.call(name, params, body, processor?) ​

The mapping lives in the one place every action already flows through. The optional fourth argument is a MessageProcessor — pass a form's JSONModel (a sap.ui.model.Model is a MessageProcessor). Added in @laravelui5/core 5.4.0 / laravelui5/core 1.4.0:

js
async call(name, params = {}, body = null, processor = null) {
    // … resolve url + method …
    if (processor) clearValidationErrors(processor);   // scoped: only this processor's marks
    try {
        return await connection[fn](url, body);
    } catch (err) {
        if (processor && err && err.status === 422 && err.cause) {
            markValidationErrors(err.cause.errors, processor);
        }
        throw err;   // rejection still propagates for the caller's fallback
    }
}

markValidationErrors turns each errors key into a binding path and builds one Message per string, targeting that path on the processor:

js
const target = "/" + key.replace(/\./g, "/");   // email → /email ; workers.0.rate → /workers/0/rate
messages.push(new Message({ message: text, type: MessageType.Error, target, processor }));
// … then: Messaging.addMessages(messages);

Two things worth knowing:

  • No registerMessageProcessor call. Messaging.addMessages reads the processor off each Message and drives its DataState directly. Registration is only needed for client-side parse/validation events (registerObject), which this does not use — these are server messages injected by hand.
  • Clearing is scoped to the processor. In an FCL two forms can be open across columns; submitting one must not wipe the other's marks. clearValidationErrors removes only the messages whose getMessageProcessor() is this model, and runs on every call — so a successful re-submit leaves a clean form without re-adding any.

4. The payoff — controls light up for free ​

Because a control bound value="{form>/email}" shares the exact model instance passed as processor, and the Message targets /email on that instance, UI5's DataState routes the message to the binding and the control renders valueState=Error automatically. A MessagePopover bound to Messaging.getMessageModel() lists every message. No per-control code.

The whole client contract is therefore the naming convention:

A control's binding path is its Laravel validation key.email ↔ {form>/email}; table rows follow the collection: workers.0.rate ↔ a cell bound within items="{form>/workers}". Get the binding path right and the field lights up; there is nothing else to wire.

The responsibility split (why the modal is not in Core) ​

  • Core call marks fields — mechanical, non-modal, imposes no UI. A caller that wants silent handling, a toast, or its own dialog is not forced into a modal.
  • The app owns the modal. In the Partners app that is one shared handler on the base controller (ui5-partners/webapp/controller/BaseController.ts):
ts
public handleActionError(err: unknown): void {
    const e = err as ActionError;
    const message =
        e?.status === 422
            ? e.cause?.message ?? "Validation failed."      // the server summary; fields already marked by call
            : err instanceof Error ? err.message
            : typeof err === "string" ? err
            : "An unexpected error occurred.";
    MessageBox.error(message);
}

On a 422 the field marks are already in place (Core did that); handleActionError adds only the general summary. Any other failure is shown verbatim.

Wiring a form ​

A field-bound form (a "form" JSONModel with inputs bound {form>/…}):

  1. Capture the model so it can be handed to call:
    ts
    const model = this.getModel("form") as JSONModel;
    const f = model.getData();
  2. Pass it as the fourth argument to every LaravelUi5.call in the submit:
    ts
    await LaravelUi5.call(SAVE_ACTION, { partner: f.partnerId }, body, model);
  3. Route the catch through the shared handler:
    ts
    } catch (err: unknown) {
        this.handleActionError(err);
    }

An action-only trigger (a delete/lock/toggle button — no bound input fields to mark) skips the processor and just adopts the handler for a consistent 422 summary:

ts
LaravelUi5.call(DELETE_ACTION, { partner: id }, { id: rowId })
    .then(/* … */)
    .catch((err: unknown) => this.handleActionError(err));

That is the entire surface. The backend needs nothing beyond extending AbstractSdkFormRequest and writing normal rules(); the validation keys it declares are the binding paths the form already uses.

Reference — where each piece lives ​

LayerRepo / fileSince
422 JSON contractlaravelui5/sdk · src/Http/Requests/AbstractSdkFormRequest.php (failedValidation)SDK 0.17.20
Error transportui5-core-lib · src/Connection.js (handleJsonResponse)pre-existing
The seamui5-core-lib · src/LaravelUi5.js (call + markValidationErrors/clearValidationErrors)@laravelui5/core 5.4.0
Bundled into Corelaravelui5/core · CoreLibrary::VERSIONCore 1.4.0
App modal policyui5-partners · webapp/controller/BaseController.ts (handleActionError)host
Consumersui5-partners · every form controller + dialogs/BaseCreateDialoghost

Version / release notes ​

  • The runtime uses the served Core bundle (core/resources/ui5, produced from ui5-core-lib/dist by the bundler), so the feature is live once Core 1.4.0 is bundled and installed in the host — no per-app change to Core.
  • The npm-published types of @laravelui5/core intentionally trail HEAD (the "npm release model": runtime rides the served bundle, the npm tag lags). A consuming app that calls call with the fourth argument must have @laravelui5/core >= 5.4.0 installed for tsc to accept it; until it does, the runtime still works (extra JS args are ignored by the old types) but ts-typecheck will flag "Expected 1-3 arguments." ui5-partners is on ^5.4.0.