Validate your own forms with OXID eShop standards

There are some very useful tools OXID ships with for form validation. They are used by the OXID eshop itself (e.g. registration form) but you can also use them for your own forms. The benefit is, that it is a 100% OXID-compliant solution and you need no third-party libraries. The tutorial should give you an idea of how to do that and is just a minimal example.

OXIDs form validation consists mainly of 2 components

  • a server side component: oxinputvalidator.php
  • a client side component: the jquery widget oxinputvalidator.js

In order to use those 2 components, you have to use your own controller (or extend an existing one). In this example, we create a new controller, which renders a simple form with one single form field. It searches for a user by its customer number and shows a success template if a user with this customer number was found. If not, it shows different error messages.

First, you have to create a module and create a form in it. This form should look like the following example. The explanation for all the necessary elements:

  • include the oxinputvalidator jQuery widget
  • Bind this OXID widget to your form element (class js-oxValidate in this example)
  • aFormData collects the form data already sent
  • aErrors gets you all the form errors detected server-side. You can call getFieldValidationErrors on every controller class (which extends oxubase) or directly on core/oxinputvalidator. The errors of aErrors are shown afterwards with the included JavaScript oxInputValidator.
  • the input element oxpsuseractivation_custnr which should be validated has to take at least the class js-oxValidate but also can take more classes like js-oxValidate_notEmpty. These classes do automatic JavaScript-Validation of the JS widget oxInputValidator. You also can give specific error-texts (in the p-tag after the input-element in the example).
  • For server-side validation, you have to create a validation function in the class oxinputvalidator (extend this class). Within this class, you can throw oxInputExceptions and retrieve them with the function getFieldValidationErrors in the frontend. The JS-widget oxInputValidator can display these errors to the assigned field (oxpsuseractivation_custnr in this example).
  • In your form controller, you have to call the validation function of oxInputValidator.

Voilà, in the following screenshot, you can see a validation error thrown by the server side component of our example:

Screenshot of OXID form validation

Error-message from OXID server side form validation