Transformer plugin

Modify the field value before doing validation

Usage

By default, the value of field will be taken by using the value property. In some case, you might want to adjust the value before performing validations. For example, the numeric validator doesn't allow to use a comma (,) for thousand separator.

The Transformer plugin allows to filter the value of field. The following piece of code is the starting point to use the Transformer plugin:

The sample code above assumes that the FormValidation files are placed inside the vendors directory. You might need to change the path depending on where you place them on the server.

FormValidation only uses the value returned by the Transformer plugin for validating. It does NOT send the modified value to the server when submitting the form.

The next sections introduce some examples demonstrating how to apply this option for popular validators.

Using with uri validator

The following form accepts a website address without http:// or https:// prefix.

By default, these kind of URLs don't pass the uri validators. Using the Transformer plugin for the uri validator, we can make it pass.

Using with numeric validator

By default, the numeric validator doesn't accept the comma. In the form below, the Price field now accepts value using comma for thousand separator, such as 12,570.634

Using with phone validator

The phone validator supports phone number in various countries. Despite the fact that it try to support many possible formats of a phone number, it can't cover all or special one which you want it to be a valid phone number.

For instance, a number containing the spaces such as XXX XXX XXXX (where X presents a digit from 0-9) is treated as invalid US phone number.

By using the Transformer plugin, we can turn this kind of number into a valid one by removing all spaces.

Using with WYSIWYG editors

WYSIWYG stands for What You See Is What You Get. A WYSIWYG editor provides a visual way to edit the content of input which mostly is a textarea element.

Since these editors usually generate additional HTML tags, the raw content of input might be different with the value returned by the editor. The notEmpty, stringLength validators maybe don't work correctly with the field using a WYSIWYG editor.

The following form uses the Transformer plugin to get raw text of a TinyMCE editor before doing validations.

Changelog

  • v1.0.0: First release

More examples