﻿var Validater = function()
{
    this.onBeforeFocus = null;
    
    this.trim = function(text)
    {
        return text.replace(/(^\s*)|(\s*$)/g, '');
    }
    
    this.failing = function(ctrl,msg)
    {
        if (this.onBeforeFocus != null)
        {
            this.onBeforeFocus();
        }
        
        ctrl.focus();
        if (ctrl.select) ctrl.select();
        
        alert(msg);
    }
    
    this.NotNull = function(ctrl,msg)
    {
        var val = this.trim(ctrl.value);
        
        if (val.length < 1)
        {
            this.failing(ctrl,msg);
            return false;
        }
        
        return true;
    }
    
    this.UpperLimit = function(ctrl,msg,limit)
    {
        var val = this.trim(ctrl.value);
        
        if (val.length > limit)
        {
            this.failing(ctrl,msg);
            return false;
        }
        
        return true;
    }
    
    this.LowerLimit = function(ctrl,msg,limit)
    {
        var val = this.trim(ctrl.value);
        
        if (val.length < limit)
        {
            this.failing(ctrl,msg);
            return false;
        }
        
        return true;
    }
    
    this.IsInteger = function(ctrl,msg)
    {
        var val = this.trim(ctrl.value);
        
        if (val.length > 0 && !val.match(/^[-,+]?\d+$/))
        {
            this.failing(ctrl,msg);
            return false;
        }
        
        return true;
    }
    
    this.IsFloat = function(ctrl,msg)
    {
        var val = this.trim(ctrl.value);
        
        if (val.length > 0 && isNaN(val))
        {
            this.failing(ctrl,msg);
            return false;
        }
        
        return true;
    }
    
    this.IsEmail = function(ctrl,msg)
    {
        var patterns = /^[a-zA-Z0-9][a-zA-Z0-9_-]*@[a-zA-Z0-9][a-zA-Z0-9_-]*(\.[a-zA-Z][a-zA-Z0-9_-]+)+$/;
        var val = this.trim(ctrl.value);

        if (val.length > 0 && !val.match(patterns))
        {
            this.failing(ctrl,msg);
            return false;
        }
        
        return true;
    }
}
