Giter Club home page Giter Club logo

validator.js's Introduction

#Introduction to Validator.js

Dependence Libraries:

##Brief Introduction Just as its name implies, Validator.js wraps some common functions used for validating user input. Aiming at simple using, Validator.js provide some clear and simple interfaces.

##Features

  1. Dynamically Validating. Listen to users' input on real-time and dynamically validate.

  2. Automatically Revising. Revise error input reasonably according to different validation rules.

  3. Switching between timer and event binding. User can choose timer or event handler to trigger validation.

  4. Detailed Validation Results Exhibition. For the condition of multi validation rules, detailed results of each validation rule will be returned.

  5. Thirty-one kinds of integrated rules.

  6. Allowing extend new rules.

  7. Receiving custom functions or regular expressions as validation rules.

##How to use An example of traditional usage is as following:

vld = new Validator([{
            field: "#text1",
            rule: ["required","max[10]"],
            msg: "This field is required.",
            tipDir: "left",
            tipOffset: {
                left: -50,
            },
            dynamicVld: true
        }, {
            field: "#text2",
            rule: ["min[3]","max[10]"],
            msg: "The input length must be between 3 and 10",
            tipOffset: {
                left: 50,
            },
            dynamicVld: true
        }], {
            vldOnBlur: true,
            errorField: "#errField",
            errorClass: "error",
            tipDir: "right",
            tipOffset: {
                left: 5,
            },
            timer: false,
            parent: $(".outer").first(),
            autoRevise: true
        });

Validator Constructor

The constructor of Validator requires two parameters: the first one is an array, which represents the collection of the validation rules, the second one is the an js object, which represents the global settings.

Options for the array, the first parameter.

Each element of the array must obey the following format:

{
    field: '', //input which needs to be validated
    rule: [], //rule for the validation.Type of Array.Each element must be string and obey this format: ruleName[parameter]
    msg: '', //error message for false validation
    tipDir:'', //location of the error tip, must be one of "up,down,left,right"
    tipOffset: {
        left: '', //left offset to the original location of error tip
        top: '' //top offset to the original location of error tip
    },
    limiter: {
        //the settings for limiter.js
    },
    dynamicVld: boolean //whether trigger dynamic validation or not
    
}

Of course you can skip some options. The default value will be used. But you must indicate two fields at least: field and rule.

Options and default value for the second parameter

{
    //version code
    version: "1.0.2", 

    //when the input label lose its focus, its own validation will be triggered
    vldOnBlur: false, 

    //Once one input field was validated as faulty, it will be checked dynamically. 
    checkOnError: true, 

    //When there are several faulty inputs fields, the first one will be focused. 
    focus1stErr:true,

    //Use time or event handler to trigger validation
    timer: true,

    //id of a DOM element which will show all the error messages 
    errorFiled: null, 

    //CSS class name which will be applied to the input label when the validation fails
    errorClass: "", 

    //CSS class name which will be applied to the errorLoc
    errorLocClass: "", 

    //template for error tip
    errTipTpl: "<div class='errorTip' style='z-index:10;"
                + "position:absolute;'>{{message}}</div>",

    //location of the error tip, must be one of "up,down,left,right"
    tipDir: "right",

    //offset to the original location of error tip, must contains "left" and "top" fields
    tipOffset: null, 

    //default error msg 
    defaultMsg: "Error Input.",

    //Parent node of the input fields of validations
    parent: "body", 

    //For the dynamic validations, use the revised value or last value to replace the wrong value. If this option is set as true, revised value will be used, otherwise, last value will be used.
    //Notice: last value may not be correct as well.
    autoRevise: false
}

You can skip all options here, because every field has its default value.

By calling vld.isPassed() to check whether all the validations are passed.

By calling vld,results() to get the detailed results.

By calling vld.revise() to manually revise.

Besides timer and event can trigger validation, validation can be called by calling vld.validateAll() or vld.validateOne(index).

API

####window.ValidatorDefaults(opts)

@param opts string

Global settings

####window.Validator(validations,opts)

As described previously

####Validator.results()

@return [] detailed validation results

####Validator.isPassed()

@return boolean whether all validations are passed or not

####Validator.validateAll()

@return boolean whether all validations are passed or not

trigger all validations manually

####Validator.revise()

@return boolean whether all validations are passed or not after revising

manually revise, then validate all

####Validator.validateOne(index)

@param index integer index of validation in the set of validations

validate one validation manually, given by index

validate single input field

$obj.validator(validation)

validator.js's People

Contributors

xiupengma avatar heatroom avatar foriacus avatar gyx1986 avatar leo1394 avatar

Watchers

James Cloos avatar  avatar

validator.js's Issues

Interval timer hasn't been destroy, when object of validator finished its job

Having tried validator test with configuration as follows:

 /* vldSettings assign each dynamicVld with true*/
    this.validator = new Validator(vldSettings, {timer: true});

I come to find that interval timer isn't cleared, which has been setup in dynamically validating, when object of validator finished its job of validating and destroyed together with object containing this validator.

source code(Validator-1.0.2) from line 484 on in function _init, interval timer has been setup for dynamic limiter check.

    /* 使用定时器还是事件绑定 */
        if (opts.timer) { //使用定时器
            //动态验证的定时器
            if (dynamicVlds.length != 0) {
                setInterval(function() {
                    for (var i = 0; i < dynamicVlds.length; i++) {
                        me._dynamicCheck(dynamicVlds[i]);
                        if(dynamicVlds[i].limiter){
                            dynamicVlds[i].textLimiter.count();
                        }
                    }
                }, CHECK_INTERVAL);
            }
            //出错时检验的定时器
            if (opts.checkOnError) {
                setInterval(function() {
                    for (var i = 0; i < validations.length; i++) {
                        if (validations[i].onError) { //onError专用于定时验证,不用passed是为了焦点不离开输入框时不取消定时器
                            me.validate(validations[i]);
                        }
                        if(validations[i].limiter){
                            validations[i].textLimiter.count();
                        }
                    }
                }, CHECK_INTERVAL);
            }

As we all know, Javascript engines only have a single thread, forcing asynchronous events (such as clicks and timers) queue waiting for execution. Timers (setTimeout(), setInterval()) in Javascript would call the specified function after the delay then end up or continually call untill it is cleared or canceled.

In a loop of event binding, error, "index out of bounds", would be thrown when event bound has been triggered in Validator

Description

An error, "index out of bounds", is thrown after I try to setup dynamic limiter check and take the option of timer, instead of the default (check only when event triggered), both of which already have been implemented by Validator.

validator settings in my trial are configured somehow like that:

  /* in vldSettings, each "dynamicVld" has been assigned with true*/
   this.validator = new Validator(vldSettings, {timer : true});

Analysis

it's quite easy to find that code (Validator-1.0.2) from line 509 to 515 is the very cause, which failed to save state of index 'i'.

 /* limiter更新 */
            for (var i = 0; i < validations.length; i++) {
                if (validations[i].textLimiter) {
                    validations[i].$el.on("keydown, paste, blur, input", function(){
                        validations[i].textLimiter.count();
                    })
                }
            }

In the loop, this doesn't work as what is expected, because the value of i never gets locked in . instead, every handle function, after any event bound has been triggered, can only find the value of i actually is validations.length at that point.

Solution

Command for are excuted sequentially, the aim of all validation would not be achieved until 'for' loop finished. at that time, the value of i has been assign with validations.length. while event handle functions could be called, after event is triggered

One kind solution,save the sate of closure by Immediately-Invoked Function Expressions(IIFE), validator could take into consideration, shown as below:

 /* limiter更新 */
for(var i = 0; i < validations.length; i ++){
    (function(lockedInIndex){
        validations[i].$el.on("keydown, paste, input, blur", function(){
            validations[lockedIndex].textLimiter.count();
        }
    })(i);
}

Just like when arguments may be passed when functions are invoked by their named identifier, they may also be passed when immediately invoking a function expression. And because any function defined inside another function can access the outer function’s passed-in arguments and variables (this relationship is known as a closure), an Immediately-Invoked Function Expression(IIFE) can be used to “lock in” values and effectively save state.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.