tFormer.js - form validation bike

    tFormer.js - empower your HTML forms


    Have you had to make up forms? Have to write a script to validate these forms on the client? Have you ever used existing plugins / add-ons to validate forms?
    I had to, but I was not 100% satisfied with either the approach to solving the problem head-on (my own validation script for each project under its forms), or the way existing third-party plugins work.


    The main problems of our own scripts and plugins have always been - flexibility, convenience and simplicity.
    A large number of data-attributes necessary for configuring scripts (as in Parsley.js) make the code less readable, and you never remember how they are all written. Not just ...
    Not all plugins fit well with the desired HTML forms, and constantly writing your own scripts under different forms is not always convenient and reasonable.


    Create something flexible, conveniently customizable, completely controllable, with an intuitive syntax and validate.


    The solution resulted in a small open source plugin called tFormer.js .

    Key features and features:

    • Independence - does not need jQuery (a rarity nowadays);
    • A large list of validation rules;
    • All validation rules are short and intuitive - easy to remember and use;
    • Combining and setting rules through just one data-attribute or through options when initializing a new tFormer object;
    • A separate object that performs the validation of values ​​itself can be used outside the main plugin or for additional complex validations;
    • "Custom" own () validation function - can be written by the developer for complex validations of a specific field;
    • Changing the rules and settings of the validator "on the fly" (setRules () and set () methods);
    • Control submit events and visual control submit buttons;
    • Buttons for checking validation (check buttons);
    • Variable validation event (the default event for validation is “input” and “keyup”);
    • Timeout validation delays;
    • Processing conditions;
    • Ability to set options for both all fields and unique for each field;
    • onerror and onvalid functions that fire after validation;
    • before function is executed every time before validation;
    • AJAX validation without strict regulations for the AJAX response (in the end (result) function, the developer must return true or false by processing the response);
    • Modification of error, processing and disabled classes;
    • … And so on.

    Installation and use:

    1. Download;
    2. Connect the script on the desired page;
    3. Define a new tFormer object with the desired options.

    Example HTML form:

    An example of a tFormer minimum definition:
    var my_form_id = new tFormer('my_form_id');

    Example of determining tFormer with indicating modifications:
    var my_form_id = new tFormer('my_form_id', {
         errorClass: 'my_own_errorClass', // новый класс для полей, которые не проходят валидацию
         timeout: 666, // валидационный таймаут
         disabledClass: 'i_am_disabled',
         onerror: function(){  // обработчик ошибок валидации
              console.log('The field with name `' + + '` is not valid');
         // другие опции ….
         fields: { // опции который относятся к конкретным полям
              email: {
                   timeout: 500 // таймаут валидации для поля email

    Summary table of validation rules:

    *required field (value cannot be empty)
    @, @s, ip, base64,urlemail, comma-separated emails, IP address, Base64 string, URL (respectively)
    <, >, >=,<=comparing field values ​​with numbers. (example " >=10" - the field value must be greater than or equal to 10)
    l=, l<, l>, l>=,l<=comparing the number of characters of a field value (example " l=5" - the value should be 5 characters)
    =, =#comparison with a specific value (' =10', ' =some_value') or with the value of some field with the specified id (' =#some_id')
    !=, !not equal to or does not contain (' !=some_value' - not equal to 'some_value', ' !.com' - does not contain '.com')
    c, cv, cm, ca,cdcredit card validation (all types, visa, mastercard, amex, discover)
    D=comparison for compliance with the date format (for example, " D=Y-M-D" - checks for compliance year-month-date)

    Pieces of code:

    Example of changing options and validation rules:
    my_form_id.set({timeout: 555}); // новый таймаут для валидации
    my_form_id.setRules(' ', 'email'); // теперь поле всегда валидно - нет правил

    A separate object for validation (used by the main plugin and can be used separately from it):
    _v_('some value').validateWithRules('* l>5'); // => true

    Custom function for validating fields of a complex type (created by the developer as 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 monitoring the state of the form:
    // активировать / деактивировать сабмит кнопку
    my_form.submitButtonControl( true ); // алиас - submitButtonOn()
    my_form.submitButtonControl( false ); // алиас - submitButtonOff()
    // включение / выключение состояния обработки у сабмит кнопки
    my_form.processing( true ); // алиас - processingOn()
    my_form.processing( false ); // алиас - processingOff()
    // блокировка и разблокировка сабмит кнопки формы
    my_form.unlock(); // что разблокировать форму надо вызвать unlock() столько раз сколько был вызван lock()

    Plugin Status:

    The plugin has stepped over version 0.3 and is now in beta.
    It works in new versions of browsers and even in IE8 (I had to get confused).
    Lies on a github, done as far as possible and time, waiting for additional ideas and commits from all interested developers :)


    Also popular now: