Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 28 ยท Controllers, Models and Templates

Forms, Validation and CSRF

Build forms in SFRA: XML form definitions, server.forms.getForm, field validation and error keys, client versus server checks, and CSRF tokens, with runnable stand-ins.

Forms are where shoppers give you data: addresses, payment details, account registration, newsletter sign-ups. They are also where a storefront is attacked most often. B2C Commerce handles this with a form framework: you describe a form in an XML file, the platform builds a form object from it, validates posted values on the server, and gives your controller and template a consistent way to read values and error messages. A second mechanism, CSRF protection, makes sure the post came from your own page.

This lesson shows the pieces and how they fit together, and why server-side validation is never optional. It follows ISML Templates because forms are rendered from templates and handled by controller routes. General input rules are in HTML Form Validation.

The form framework and CSRF helpers exist only on the platform, so the real XML and controller code is read-only. The runnable examples are stand-ins: a validator driven by a data definition, and a session-bound token check. The hash used in the CSRF stand-in is a toy and is not real security.

A form definition

Each form is an XML file in cartridge/forms/default/ (locale folders can override). The file name is the form name:

XML
<?xml version="1.0"?>
<!-- Read-only: cartridge/forms/default/newsletter.xml -->
<form xmlns="http://www.demandware.com/xml/form/2008-04-19">
  <field formid="email" label="label.input.email" type="string" mandatory="true"
         max-length="30" regexp="^[^@\s]+@[^@\s]+\.[a-zA-Z]{2,}$"
         missing-error="error.message.required"
         parse-error="error.message.parse.email"
         range-error="error.message.30orless"/>

  <field formid="age" label="label.input.age" type="integer" min-value="18" max-value="120"
         parse-error="error.message.parse.number"
         value-error="error.message.age.range"/>

  <field formid="consent" label="label.input.consent" type="boolean" mandatory="true"
         missing-error="error.message.required"/>
</form>

Important parts:

  • formid is the field's name inside the form.
  • type is string, integer, number, boolean, date and so on. It controls parsing: a non-number in an integer field is a parse error.
  • mandatory, max-length, min-length, min-value, max-value and regexp are the validation rules.
  • The ...-error attributes hold resource keys, not text. The text lives in a properties file so it can be translated.
  • Forms can also contain <group>, <list> and <action> elements to nest fields and describe buttons.

Because the rules are data, an overlay cartridge can change a form (for example make a phone field mandatory) by providing a file with the same name earlier in the cartridge path.

Using a form in a controller

JavaScript
// Read-only: cartridge/controllers/Newsletter.js (illustrative)
'use strict';

var server = require('server');
var csrfProtection = require('*/cartridge/scripts/middleware/csrf');

server.get('Show', server.middleware.https, csrfProtection.generateToken, function (req, res, next) {
    var newsletterForm = server.forms.getForm('newsletter');
    newsletterForm.clear();

    res.render('newsletter/signup', { newsletterForm: newsletterForm });
    next();
});

server.post('Subscribe', server.middleware.https, csrfProtection.validateAjaxRequest, function (req, res, next) {
    var newsletterForm = server.forms.getForm('newsletter');

    if (!newsletterForm.valid) {
        res.json({ success: false, fields: collectErrors(newsletterForm) });
        return next();
    }

    var email = newsletterForm.email.value;
    // ...save the subscription, call a service...
    res.json({ success: true });
    return next();
});

module.exports = server.exports();

server.forms.getForm('newsletter') returns a form object. After a POST, the platform has parsed the submitted values into it, so form.valid tells you whether all rules passed, and each field exposes value, valid and error (the resource key). SFRA ships a helper (formErrors.getFormErrors(form)) that collects the errors into an object the front end can show next to each input. Look in your base cartridge for its exact signature.

Calling form.clear() on the GET route makes sure leftovers from an earlier submission do not leak into a new page.

flowchart LR
    X["forms/default/newsletter.xml"] --> F["server.forms.getForm('newsletter')"]
    F -->|"GET"| T["Template renders inputs<br/>(htmlName, labels)"]
    T --> B["Browser"]
    B -->|"POST with CSRF token"| C["Controller route"]
    C --> V{"form.valid?"}
    V -->|"no"| E["JSON with field errors"]
    V -->|"yes"| S["Save and respond"]

The same definition drives the rendered inputs and the server-side validation.

Rendering fields

In the template, use the form object so names, labels and values stay in sync with the definition:

HTML
<!-- Read-only: templates/default/newsletter/signup.isml (simplified) -->
<form action="${URLUtils.url('Newsletter-Subscribe')}" method="post" name="${pdict.newsletterForm.htmlName}">
  <label for="email"><isprint value="${Resource.msg('label.input.email', 'forms', null)}" /></label>
  <input type="email" id="email" name="${pdict.newsletterForm.email.htmlName}"
         value="${pdict.newsletterForm.email.htmlValue}" required maxlength="30">
  <div class="invalid-feedback"></div>

  <input type="hidden" name="${pdict.csrf.tokenName}" value="${pdict.csrf.token}"/>
  <button type="submit">Subscribe</button>
</form>

htmlName is the generated name the platform recognizes on the way back in (it begins with dwfrm_). Do not invent your own input names for fields that the form framework should parse. Let the form object produce them.

Client-side versus server-side validation

SFRA applies HTML5 attributes (required, maxlength, pattern) and some JavaScript in the browser to give quick feedback. That is convenience, not security. Anyone can send a request without your page, with a tool such as curl, so the server must always check again. The form framework does that for you, but only if the controller actually reads form.valid and acts on it.

A good pattern:

  1. Validate on the client for instant messages.
  2. Validate on the server with the form definition and return field errors as JSON.
  3. Show server errors next to the fields. Never trust that "the browser already checked".
  4. Also validate business rules the definition cannot express (for example a coupon that is expired) in the controller or helper.
JS A definition-driven form validator (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the output holds resource keys (error.message.parse.email), not sentences. The template or the front-end script looks the key up in the shopper's language.

CSRF: making sure the post came from you

Cross-site request forgery tricks a logged-in shopper's browser into sending a request to your site from another site. Because the browser attaches cookies automatically, the server sees a valid session and may perform the action (change an address, place an order). A CSRF token stops that: it is a secret value tied to the shopper's session, placed in the form as a hidden field, and required on every state-changing request. A foreign site cannot read your page, so it cannot know the token.

In SFRA the pieces are:

  • csrfProtection.generateToken (middleware on the GET route) creates a token and exposes it as pdict.csrf.tokenName and pdict.csrf.token.
  • The template writes it into a hidden input, or into the page for AJAX requests.
  • csrfProtection.validateRequest or validateAjaxRequest (middleware on the POST route) checks it. If it is missing or wrong, the request is rejected before your handler runs. These helpers build on the platform's dw.web.CSRFProtection class.

Tokens are only a defense when every state-changing route uses them. One forgotten POST route is enough.

JS Session-bound CSRF tokens (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The token is bound to the session, so a token copied from one shopper does not work for another. The details of cookies, sessions and attacks continue in Security, Sessions and Compliance.

Error handling checklist

  • Return a clear JSON shape (success, fields, error) for AJAX posts, and re-render the page with messages for normal posts.
  • Do not reveal internals in error text, and never echo submitted values without encoding them.
  • Log unexpected failures (see Testing, Debugging and Logging), but never log passwords or card data.
  • Redirect after a successful normal POST so a refresh does not resubmit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where are the validation rules of an SFRA form defined?

    The XML definition lists fields, types and rules, and the framework validates posted data against it on the server.
  2. 2. Why must you validate on the server even if the page uses required and pattern attributes?

    Anyone can send a crafted request, so the server must enforce the rules.
  3. 3. What do attributes like missing-error="error.message.required" contain?

    Errors are keys, so messages can be localized and changed without touching the form definition.
  4. 4. What does a CSRF token protect against?

    A foreign site cannot read the token from your page, so forged requests fail validation.
  5. 5. In which place must CSRF validation be applied?

    A single unprotected state-changing route can be abused, so apply validation consistently.

Summary

  • A form is an XML definition with typed fields, rules and error resource keys; server.forms.getForm gives controllers and templates one shared form object.
  • Use form.valid and field error values on the server and return structured errors to the front end.
  • Render inputs from the form object (htmlName), and call form.clear() for fresh GET requests.
  • Client validation gives fast feedback but never replaces server validation.
  • CSRF tokens tie a request to the shopper's session; generate them on GET routes and validate on every state-changing route.

Next: The Script API and Common Classes