/** * @fileoverview * Javascript main code. */ function Validator() { }; function ValidateRegex(regex) { this.regex = new RegExp(regex); }; ValidateRegex.prototype = new Validator(); ValidateRegex.prototype.constructor = ValidateRegex; ValidateRegex.prototype.isOk = function(input) { var res =this.regex.test(input); return {result: res ,message: input + " does "+ (res? "" : "not")+ " match "+this.regex}; }; function ValidateRange(from,to) { this.from(from || -Number.MAX_VALUE); this.to(to || Number.MAX_VALUE); }; ValidateRange.prototype = new Validator(); ValidateRange.prototype.constructor = ValidateRange; ValidateRange.prototype.isOk = function(input) { var res = input >= this._from && input < this._to; return {result: res, message: (res ? input + " is within "+this._from +" and "+this._to : input + " is not within "+this._from +" and "+this._to)}; }; ValidateRange.prototype._setBounds = function(bound,val) { var fun = function() { return val; }; if(typeof val == 'function') fun = val; this.__defineGetter__(bound,fun); return this; }; ValidateRange.prototype.from = function(lb) { return this._setBounds("_from",lb); }; ValidateRange.prototype.to = function(ub) { return this._setBounds("_to",ub); }; ValidateRange.prototype.toString = function() { return "[" + this._from + ","+this._to+"]"; }; function BinaryOp(left,right) { this.left = left; this.right = right; }; BinaryOp.prototype = new Validator(); BinaryOp.prototype.constructor = BinaryOp; BinaryOp.prototype.isOk = function(input) { var left = this.left.isOk(input); var right = this.right.isOk(input); return {result: this._eval(left,right), message: this._message(left,right)}; }; function And(left,right) { BinaryOp.call(this,left,right); }; And.prototype = new BinaryOp(); And.prototype.constructor = And; And.prototype._eval = function(left,right) { return left.result && right.result; }; And.prototype._message = function(left,right) { return (left.result ? (right.result ? left.message +" and " + right.message : right.message) : left.message); }; function Or(left,right) { BinaryOp.call(this,left,right); }; Or.prototype = new BinaryOp(); Or.prototype.constructor = Or; Or.prototype._eval = function(left,right) { return left.result ||right.result; }; Or.prototype._message = function(left,right) { return (left.result ? left.message : (right.result ? right.message : left.message +" and " + right.message) ); }; function Not(sub) { this.sub = sub; }; Not.prototype = new Validator(); Not.prototype.constructor = Not; Not.prototype.isOk = function(input) { var res = this.sub.isOk(input); return {result: !res.result, message: res.message}; }; function beANumber() { var val = new Validator(); val.isOk= function(input) { return { result: !isNaN(input), message: input +" is "+ this.result ? "" : "not"+ " a number" }; }; return val; };