Bwf/ GuideFrançais
Bwf Guide

Validation and error responses

Try submitting three spaces as an article title. We’ll see where the Journal catches that mistake, then follow a registration error all the way back to its field in the form.

What the action receives

The decoder can give the action a string and still leave a little work to do. We want an article title that has something in it after trimming. The action has the value in hand and can make that decision before it saves the article.

Django form validation

What the contract accepts

In the Journal’s ArticleForm schema, title, description, and body are required strings. A title consisting of three spaces is a string. Model/Article/Draft.bend trims it and enforces the 200-character limit.

The schema rejects a misspelled key such as titel because the required key is missing and additional properties are disallowed. The same rule applies to a request sent directly to the server.

type: object
additionalProperties: false
required: [title, description, body]
properties:
  title: {type: string}
  description: {type: string}
  body: {type: string}
  tags: {type: string}

What’s left after trimming?

Keep the submitted draft available while you check it. Run the two lines below with the three spaces as raw_title. The cleaned string has length zero, so empty is true.

At this point return the error declared by the operation. The reader can correct the draft. With a nonempty title, use the trimmed value for the write.

clean_title = String.trim(raw_title)
empty = String.is_empty(clean_title)

Declare a response for invalid input

In examples/canonical/openapi.yaml, POST /register takes a URL-encoded form. Bwf generates Api.Registration from the schema and decodes the request before calling the controller. A missing required field can produce a 422 with a text/plain body before the controller runs.

Declare a 422 HTML response for decoded values that fail a rule in the controller. With x-bwf-htmx: true, Bwf also generates a constructor for returning the form fragment.

x-bwf-htmx: true
responses:
  '422':
    description: The submitted form and its field errors.
    content:
      text/html:
        schema: {type: string}

Attach an error to the field

The Journal trims the username before validating it. The username . decodes as a string. The controller rejects it because the Journal reserves that segment in profile URLs.

To report the error, use the field generated from OpenAPI. Form.State holds the submitted form and its errors for the request. Pass that state to the view so it can render the values alongside their messages.

error = Api.error_Registration(
  Api.RegistrationFieldUsername{}, "Enter a valid username")
state = Form.attach_failure(~Api.Registration, error, Form.State{input, []})
form = AccountView.registration_form(state)

In the registration Submit.bend, the Journal collects errors for the username, email address, and password before choosing whether to render the form or create the account. For the approach that inspired this state, see attaching validation errors to an IHP model.

Return the form with its errors

In View/Account.bsx, pass the state and the BSX view function to Form.render. Bwf finds the control by name="username", places the message near it, and connects them with aria-describedby. aria-invalid marks the control as invalid.

def registration_form(state: Form.State<Api.Registration>) -> Html.Html:
  Form.render(~Api.Registration, state, registration_fields)

Both responses reuse the same form. A regular POST receives the full page with the submitted username and email address and an empty password field. HTMX receives the fragment and preserves the values in the controls. If a field has changed since submission, HTMX drops the message for its earlier value.

def rejected(fragment: Bool, form: Html.Html) -> Api.RegisterResponse:
  match fragment:
    case True{}: Api.Register422Fragment{form}
    case False{}: Api.Register422{AccountView.registration_page(form)}

Configure the default error renderer

Define a renderer in Config.bsx. In RouteBindings.bend, the Journal passes ~Config.field_error to Router.dispatch_with_form_theme. This setting applies to HTML 422 responses for both pages and fragments.

def field_error(message: String) -> Html.Html:
  <span class="journal-field-error">{message}</span>

Choose where a field shows its message

To place the password message inside its field group, mark the group with data-bwf-field and choose an element with data-bwf-field-error. Bwf reads the control’s name in that group, inserts the message into the chosen element, and removes hidden. The view chooses the element, CSS class, and placement.

<div class="field" data-bwf-field="true">
  <label for="registration-password">Password</label>
  <input id="registration-password" name="password" type="password" />
  <span data-bwf-field-error="true"
        class="registration-password-error" hidden></span>
</div>

Try the form in the Journal

  1. Run scripts/bwf dev from the repository root, then open the local registration form.
  2. Enter . as the username, a unique test email address, and a password of at least eight characters.
  3. Select Create account. Check for Enter a valid username near the field. The Network panel shows a 422 response with an HTML fragment.
  4. Choose an available username and submit again. The Journal creates the account and returns you to the home page.

To see a message in the custom password slot, try a 257-character password. The controller enforces a 256-character limit.

See HTML forms and CSRF for the submission contract and IHP’s guide to placing field errors for the rendering pattern that inspired this chapter.

Handle a conflict at write time

Two concurrent registration requests can both check that a name is available. The PostgreSQL uniqueness constraint decides which insert succeeds. The Journal uses ON CONFLICT DO NOTHING RETURNING id and returns 409 if the username or email address is already in use.

Try it in the Journal

Register two readers