Cookies help us deliver our services.

By using our services, you agree to our use of cookies. Learn more

I understand

In the previous article (Create a reusable AlloyUI custom validator) we saw how to create a reusable custom validator with AlloyUI; using the same principle, I want to show you how to validate a combo, integrating with the form validator.

The main problem related to the validation of a combo is that you cannot place the aui:validator taglib within the aui:select; so the only way to solve the problem would be to attach to the change event, but without the integration with the form validation, and writing so much and unnecessary Javascript code.

Thanks to the A.mix function we have already seen, we can solve the problem in a much more elegant way.

First we have to define our custom validation rule and add it to the Liferay validator, but we already know how to do it.

AUI().use('aui-form-validator', function(A) {
    var defaultFormValidator = A.config.FormValidator;

            myFunc: function (value, fieldNode, ruleValue) {
                // Validation code which returns true/false

            myFunc: Liferay.Language.get('please-select-a-valid-value')

Let's review how the A.mix function works:

  1. we retrieve the instance of the FormValidator global object configuration of AlloyUI; then, through the mix function we inject new features inside the validator;
  2. the first call of the mix function is used to add to the validator rules (RULES field) a new validation function called myFunc;
  3. the second call of the mix function is used to add to the validator messages (STRINGS field) a new translation for the error message; the translation key must be defined at the portal level, so in files;
  4. the third boolean parameter true of each call is only used to overwrite any existing definitions.

At this point, as we cannot use the aui:validator taglib, we must write a little bit of code to retrieve the rules associated to the form field that you want to validate and add the custom rule to it.

var myRules = {
    required: true,
    myFunc: true

var form = Liferay.Form.get('<portlet:namespace />fm');
var formRules = form.formValidator.get('rules');

formRules['<portlet:namespace/>myCombo'] = myRules;

First we create a simple myRules object, where the field names are the names of the validation rules we want to apply (required and myFunc); then we retrieve the instance of the form we need to validate and the object that represents all the related validation rules, formRules.

This object is nothing more than an associative array where the keys are the form field names and the values are the rules to be applied; therefore it is sufficient to assign the myRules object to the correct field.