Validating Form Data

Server-side validation on form data is configured in the form definition. SFRA uses jQuery AJAX methods to render a page after server-side validation.

Validation by Attribute

The attributes set on the form field are used for validation. In the following example, the mandatory attribute requires a value for the field. The regexp attribute determines the content of the field. And the max-length attribute sets the maximum length of the data for the field.
Note: The max-length attribute is used only for validation of strings. For other field types, it's used only to format the field length and not to validate data.
<field formid="email" label="contactus.email.label" type="string" mandatory="true" regexp="^[\w.%+-][email protected][\w.-]+\.[\w]{2,6}$" max-length="50"/>
Errors shown for attribute validation:
  • Default error for form invalidation: value-error
  • Mandatory flag invalid: missing-error

  • Entered value invalid: parse-error

Validation by Function

You can also use the validation attribute to specify a function to run to validate form data. You can run these validations on container elements, such as form or group, or on individual fields.

<field formid="password"
       label="label.password"
       type="string"
       range-error="resource.customerpassword"
       validation="${require('~/cartridge/scripts/forms/my_custom_script.ds').my_custom_validation(formfield);}"

You can also selectively invalidate form elements using the InvalidateFormElement pipelet in pipelines or the invalidateFormElement function in the FormModel or any model that requires it. If any element in a form is invalid, the entire form is invalid. However, in your form definition, you can create error messages that are specific to a field. See the example of range-error, which points to a resource string with a message for the customer on why the field is invalid.

Client-Side Validation Scripts

Simple forms are standard HTML forms, so you can use any client-side validation method you choose. B2C Commerce uses default HTML5 validation for client-side validation. You can find the client-side JavaScript for a page by identifying the script added by the assets.AddJs function.

B2C Commerce provides two utility scripts you can use for validating form data:
  • form-validation: This script validates a specific field in the form. It uses the validation criteria set in the form definition and included in the attributes for the form JSON object. This script is required by the client-side JavaScript doing the validation for a specific form and is loaded at document.ready. This file is located in app_storefront_base/cartridge/client/js/default/components/form-validation.js.
  • client-side-validation: This script validates the entire form and clear a form for validation. This file is required by main.js. It is located in app_storefront_base/cartridge/client/js/default/components/client-side-validation.js