Clientside validation for Drupal 8

We just released the first release candidate of clientside validation for Drupal 8.

Drupal 8 ClientSide validation

Since Drupal 8 now has build in support for HTML5 elements, porting was a bit easier. We also took the opportunity to clean up the code, so the Drupal 8 port is a fresh start and - for the moment - there's no upgrade path for all Drupal 7 settings.

The module has been split in 2 parts to make it easier to use a different javascript library.

The main module

The main module handles the validator plugins and adds data attributes to the HTML of the form elements. Other modules can easily define their own Plugins, as an example we use a fictious credit card form element.

Create a file src/Plugin/CvValidator/CreditCard.php containing the following code

<?php
/**
 * @file
 * Contains \Drupal\creditcard\Plugin\CvValidator\CreditCard.
 */

namespace Drupal\creditcard\Plugin\CvValidator;

use Drupal\clientside_validation\CvValidatorBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'creditcard' validator.
 *
 * @CvValidator(
 *   id = "creditcard",
 *   name = @Translation("CreditCard"),
 *   supports = {
 *     "types" = {
 *       "creditcard"
 *     }
 *   }
 * )
 */
class CreditCard extends CvValidatorBase {

  /**
   * {@inheritdoc}
   */
  protected function getRules($element, FormStateInterface $form_state) {
    return [
      'rules' => [
        'creditcard' => TRUE,
      ],
      'messages' => [
        'creditcard' => $this->t('@title does not contain a valid credit card number.', ['@title' => $element['#title']]),
      ],
    ];
  }

}

The annotation is used to detect which plugin supports which kind of form element types, it can also define which HTML5 attributes are supported.

The jquery.validate module

This modules adds the necessary javascript files, it either uses the locally installed libraries or it uses the CDN version.

If your module needs the additional jquery validate methods to work, it can implement hook_clientside_validation_validator_info_alter to load the javascript.

Best to do it in a sub module, so it only gets loaded when jquery.validate is used.

/**
 * Implements hook_clientside_validation_validator_info_alter().
 */
function creditcard_jquery_clientside_validation_validator_info_alter(&$validators) {
  $validator['creditcard']['attached']['library'][] = 'clientside_validation_jquery/jquery.validate.additional';
}

Testing

If you want to test clientside validation for Drupal 8, you can start a demo at simplytest.me.

Contribute

If you want to help out, or if you find bugs, have a look at Port to Drupal 8.