tformer.js - empower your HTML forms
Apr 25, 2013     11:11:11

Introduction:

Have you ever tried to develop forms? Or wrote a script for the validation of these forms on the client side? Did you have to use the already existing plugins for form validation?

I had to, but I've never been 100% satisfied with any approach to neither solving the problem directly (own validation script for each project under its forms), nor how the existing third-party plugins works.


The Problem:

The main problems of own scripts and plug-ins have always been - the flexibility, convenience and simplicity.

A large number of data-attributes, required for configuration scripts (as in Parsley.js) makes the code less readable, and never remembers how to write them correctly. Not so simple ...

Not all plugins are well suited for the desired HTML-forms, and constantly write own scripts for different forms are not always convenient and reasonable.


Objective:

Create something flexible, easily configurable, a fully controllable, with an intuitive syntax and the main idea - to validate.


Solution:

The solution resulted in a small opensorce plugin, called tFormer.js.


Key features:

  • Independence — no needed in jQuery (rare feature nowadays);
  • A long list of validation rules;
  • All validation rules are short and intuitive - easy to remember and use;
  • Combining and setting rules in just one data-attribute or in the option when initializing the new tFormer object;
  • A separate objects for validation of values (can be used outside the main plugin or in some complex validations);
  • Custom validation function (own()) — may be written by the developer for complex validations specific field;
  • Changing rules and settings validator "on the fly" (methods setRules() and set());
  • Control submit event and visual control of submit button;
  • Buttons to check the validation (check buttons);
  • Variable validation event (by default it's "input" and "keyup");
  • Delays validation by timeout;
  • Processing conditions;
  • The possibility of set options for all the fields and unique for each field;
  • onerror() and onvalid() functions which will be triggered after the validation;
  • before() function is performed before each validation;
  • AJAX validation without strict rules for the AJAX answer (in the end(result) function developer should return true or false, after handling the result);
  • Modification of the error, processing and disabled classes;
  • ... etc.

Installation and use:

  • Download;
  • Connect script to the desired page;
  • Define a new tFormer object with the desired options.

HTML-form example:

<form id="my_form_id">
    <input type="text" name="zip" data-rules="a1 l=5" />
    <input type="text" name="email" data-rules="* @" />
    <input type="submit" value="Submit" />
</form>

An example of minimal tFormer definition:

var my_form_id = new tFormer('my_form_id');

An example tFormer definition width modifications:

var my_form_id = new tFormer('my_form_id', {
    errorClass: 'my_own_errorClass', // new class for fields that do not pass validation
    timeout: 666, // validation timeout
    disabledClass: 'i_am_disabled',
    onerror: function(){  // validation error handler
        console.log('The field with name `' + this.name + '` is not valid');
    },
    // other options ….
    
    fields: { // options that apply to specific fields
        email: {
            timeout: 500 // validation timeout for an email field
        }
    }
}); 

Short table with validation rules details:

Rules Description
* required field (the value shouldn't be empty)
@, @s, ip, base64, url email, emails (separated by commas), IP address, Base64 string, URL (accordingly)
<, >, >=, <= comparing the value of the field with numbers. (">=10" - the value should be more or equal to 10)
l=, l<, l>, l>=, l<= comparison the value.length with rule parametter ("l=5" - value length should be equal to 5)
=, =# comparing with a specific value ('=10', '=some_value') or with the value of a field with the specified id ('=#some_id')
!=, ! not equals, not contain ('!=some_value' - not equals to 'some_value', '!.com' - not containing '.com')
c, cv, cm, ca, cd credit card validation rules (all types, visa, mastercard, amex, discover)
D= comparison with the defined date format("D=Y-M-D" - checks for accordance to year-month-day)

Pieces of code:

An example of changing the options and validation rules:

my_form_id.set({timeout: 555}); // new validation timeout
my_form_id.setRules(' ', 'email'); // now the field is always valid - no rules

A separate objects for validation (used by the base plugin and can be used separately):

_v_('some value').validateWithRules('* l>5'); // => true

Custom validation function for the complex type fields (created by the developer if necessary):

var my_form = tFormer('my_form_id', {
    fields: {
        field_name: {
            own: function(){
                var my_value = this.value;
                var is_ip = _v_(my_value).validateWithRules('* ip');
                var is_email = _v_(my_value).validateWithRules('* @');
                var is_url = _v_(my_value).validateWithRules('* url');
                return (is_ip || is_email || is_url);
            }
        }
    }
});

Methods for the form state control:

// activating / deactivating the submit button
my_form.submitButtonControl( true ); // alias - submitButtonOn()
my_form.submitButtonControl( false ); // alias - submitButtonOff()

// enabling / disabling processing state for submit button
my_form.processing( true ); // alias - processingOn()
my_form.processing( false ); // alias - processingOff()

// locking and unlocking the submit button
my_form.lock();
my_form.unlock(); // to unlock the form you need to execute unlock() so many times as lock() been called

Plugin status:

Plugin crossed version 0.3 and is now in beta.

Working in new versions of browsers and even in IE8 (had to suffer a bit).

Lies on Github. Developed in a free time. Waiting for additional ideas and commit from all interested developers :)


Links:


blog comments powered by Disqus