Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
- <title>teszt</title>
- <style type="text/css">
- #fm {width:500px;display:block;margin:0; padding:0;}
- #fm label, #fm input {display:inline;float:left;position:relative;margin:0 0 5px 5px; padding:0;font:normal 12px Verdana;}
- #fm label {width:200px; font-weight:700; text-align:right;}
- #fm input {width:250px; text-align:left;}
- #send {width:60px !important;font-weight:700 !important;text-align:center !important; margin-left:200px !important;}
- #log {width:500px;height:100px;display:block;float:left;position:relative;}
- #errorMsg {
- width:300px;height:100px;left:300px;top:200px;display:block;position:fixed;
- text-align:center;vertical-align:middle; border:2px solid #F5F5F5; background:#DDD;
- }
- .failed{background:#FEE;}
- .succeeded{background:#EFE;}
- </style>
- <script type="text/javascript">
- // Necessary functions for formChecker
- // shorthand for getElementById
- function $lm(obj){
- if ( document.getElementById(obj) ) return document.getElementById(obj);
- else return false;
- }
- // object's first child with the given class
- function firstChildofClass(p,cl) {
- if (!p || !p.childNodes.length)return;
- var ch = p.childNodes;
- for ( var i = 0; i < ch.length; i++ ){
- if (gotClass(ch[i],cl))return ch[i];
- }
- return;
- }
- // shorthand for firstChildOfClass
- function $fc(p, cl){
- return firstChildofClass(p,cl);
- }
- function gotClass(obj,cl) {
- var r = new RegExp("\\b" + cl + "\\b", "i");
- var ob = ( typeof(obj) == "object" ) ? obj : $lm(obj);
- if ( ob && ob.className && ob.className.match(r) !== null ) return true;
- return false;
- }
- // object's all children with given class
- function getChildElementsByClassName(obj,cl){
- var oc = ( obj != undefined ) ? obj.childNodes : document.body.childNodes;
- var ch = [];
- for ( var i = 0; i < oc.length; i++ ){
- if (gotClass(oc[i],cl)) ch.push(oc[i]);
- }
- return ch;
- }
- // shorthand for getChildElementsByClassName
- function $cc(obj,cl){
- return getChildElementsByClassName(obj,cl);
- }
- // shorthand for parseFloat
- function pf(n){return parseFloat(n);}
- // set object's css style
- function setStyle(obj,st,vl){
- var a = obj.style.cssText;
- obj.style.cssText = (a.length>0) ? a + ";" + st + ":" + vl : st + ":" + vl ;
- }
- // trim and compress spaces
- String.prototype.clean = function(){
- return this.replace(/^(\s+)/g,"").replace(/(\s+)$/g , "").replace(/\s\s+/g , " ");
- }
- // add given class to object's className
- function addClass(obj,c){
- obj.className = (obj.className.length > 0) ? obj.className + " " + c : c;
- }
- // remove given class from object's className
- function removeClass(obj,c){
- var r = new RegExp("(\\b" + c + "\\b)", "gi");
- obj.className = obj.className.replace( r , " " ).clean();
- }
- /* formChecker class definition
- * parameters:
- * fm - the form to be verified
- * rule - form rules in JSON format
- * rule record (object) properties:
- * sbj - input class
- * if the form contains more than one input of the same class, each one will be verified
- * fnc - verifier function (these are methods of the chk() object class)
- * see functions for more details
- * prm - value to verify against
- * can be a fixed value or a form elem value defined by class or id (css-like definitions -> ".myclass" or "#myid")
- *
- * usage:
- * 1) design your own checker functions into chk() class definition if necessary
- * 2) design your own rules
- * 3) design callback functions (init, success, failure, error)
- * 4) insert init code
- *
- * for live example see my pastebin
- *
- **/
- function formChecker(fm,rule,cf,sf,ff,ef){
- if (!fm) return;
- this.fm = fm; // form DOM object
- this.rule = rule; // rule JSON object-list
- this.res = []; // result array
- this.nof = 0; // number of fails
- if ( cf == undefined || typeof cf != "function" )cf = null;
- if ( sf == undefined || typeof sf != "function" )sf = null;
- if ( ff == undefined || typeof ff != "function" )ff = null;
- if ( ef == undefined || typeof ef != "function" )ef = null;
- this.chk = function(){
- var r,val,lm,c,prm;
- // clear earlier results
- cf(this.fm);
- // rules
- for (var i in this.rule){
- r = this.rule[i];
- // check only if object exists
- if ( $fc(this.fm,r.sbj) ){
- // handle parameters
- // only try to find css-like object reference, if not number and not regexp
- // css-style DOM reference lookup with ".myclass" and "#myid"
- prm = r.prm;
- if ( isNaN(prm) && r.fnc != "rg" ){
- // ".myclass"
- if ( /^\.\w+$/i.test(prm) ){
- var tst = true;
- // only first object of the same class
- if ( $fc( this.fm , prm.substr(1) ) )prm = $fc( this.fm , prm.substr(1) ).value;
- }
- // "#myid"
- else if ( /^#\w+$/i.test(prm) ){
- var tst = true;
- if ( $lm( prm.substr(1) ) )prm = $lm( prm.substr(1) ).value;
- }
- }
- // if there's more than one input of the same class, verify each
- lm = $cc(this.fm,r.sbj);
- for (var i = 0; i < lm.length; i++){
- c = new chk(lm[i]);
- try{
- val = c.exec(r.fnc,prm);
- // fail
- if(!val){
- // use "&prm" in msg to feedback actual value from "prm"
- var msg = r.msg.replace( new RegExp("&prm", "gi"), prm);
- ff(lm[i],msg);
- this.nof++;
- }
- // success
- else sf(lm[i],"");
- } catch(er) {
- // error
- val = ef(er);
- }
- this.res.push(val);
- }
- }
- }
- return this.nof;
- }
- }
- // Compare functions for formChecker
- function chk(obj){
- this.v = (obj.value) ? obj.value : obj.innerHTML;
- // numeric "equals"
- this.eq = function(b){
- if (pf(this.v) == pf(b))return true;
- return false;
- }
- // string equals ("exact")
- this.ex = function(b){
- if (this.v == b)return true;
- return false;
- }
- // numeric "lesser than"
- this.lt = function(b){
- if (pf(this.v) < pf(b))return true;
- return false;
- }
- // numeric "lesser or equals"
- this.le = function(b){
- if (pf(this.v) <= pf(b))return true;
- return false;
- }
- // numeric "greater than"
- this.gt = function(b){
- if (pf(this.v) > pf(b))return true;
- return false;
- }
- // numeric "greater or equals"
- this.ge = function(b){
- if (pf(this.v) >= pf(b))return true;
- return false;
- }
- // empty ?
- this.nn = function(){
- if (this.v.toString().length > 0)return true;
- return false;
- }
- // regexp pattern
- this.rg = function(b){
- var bb = new RegExp(b[0],b[1]);
- return bb.test(this.v);
- }
- this.exec = function(f, arg) {
- return this[f](arg);
- }
- }
- // End of formChecker class definition
- /* Rule examples
- Notes:
- The first example refers to both inputs named "nm". It checks if inputs called "nm" are empty.
- The second one has a param that refers to the value of the elements with "minyr" css class. If there are more than one, formChecker tries to check against each.
- Numeric checks are:
- eq = equals
- ne = not equals
- gt = greater than
- ge = greater than or equal
- lt = less than
- le = less than or equal
- The third one has a param that refers to the value of the element with "maxyr" css id. Since css id is supposed to be unique, formChecker does not try to search for more than one.
- The fifth rule sets a pattern to use regexp comparison.
- If you are not familiar with regexp, you can use simple string comparison like in the sixth rule. "ex" means "exact" - just like in ms excel.
- The seventh rule should raise an error, since there is no comparison function like "dd".
- Note that one of the major advantage of using JSON is that it can be sent to the client by the server.
- This structure allows you to download rules and check locally before sending the form's data back.
- This design can lift some weight from your backend (of course you can not spare checks on the server side).
- */
- myRule = {
- first: {
- sbj: "nm",
- fnc: "nn",
- prm: "",
- msg: "Name can not be empty."
- },
- second: {
- sbj: "yr",
- fnc: "gt",
- prm: ".minyr",
- msg: "Must be over &prm."
- },
- third: {
- sbj: "yr",
- fnc: "lt",
- prm: "#maxyr",
- msg: "Must be under &prm."
- },
- fourth: {
- sbj: "cn",
- fnc: "nn",
- prm: "",
- msg: "Country can not be empty."
- },
- fifth: {
- sbj: "cn",
- fnc: "rg",
- prm: ["^hu\s*$","i"],
- msg: "Only for hungarian residents."
- },
- sixth: {
- sbj: "cn",
- fnc: "ex",
- prm: "hu",
- msg: "Only for citizens of republic of Hungary."
- }/*,
- seventh: {
- sbj: "cn",
- fnc: "dd",
- prm: "hu",
- msg: "Errorous rule."
- }*/
- }
- window.onload = function(){
- setElem = function(o,msg,cl){
- var s = "\n";
- if (!o.title || o.title == "" || msg == undefined || msg == "")s = "";
- o.title += s + msg;
- removeClass(o,"succeeded");
- removeClass(o,"failed");
- addClass(o,cl);
- }
- // function to clear given form's inputs
- // defined for formChecker to run on reset
- clear = function(fm){
- var lm = fm.getElementsByTagName("*");
- for (var i = 0; i < lm.length; i++){
- try {
- lm[i].title = "";
- removeClass(lm[i],"succeeded");
- removeClass(lm[i],"failed");
- }catch(e){
- continue;
- }
- }
- }
- // callback to execute on successful check
- success = function(o,msg){
- var c = "succeeded";
- if(gotClass(o,"failed"))c = "failed";
- setElem(o,msg,c);
- }
- // callback to execute on failed check
- fail = function(o,msg){
- setElem(o,msg,"failed");
- }
- // callback to execute on error
- error = function(er){
- if ( !$fc(document.body,"errorMsg") ){
- var ed = document.createElement("div");
- ed.className = "errorMsg";
- ed.title = "click to disappear";
- ed.innerHTML = er;
- document.body.appendChild(ed);
- ed.onclick = function(){ document.body.removeChild(ed); }
- }
- else $fc(document.body,"errorMsg").innerHTML += "<br>" + er;
- }
- var sn = $lm("send");
- var fm = $lm("fm");
- var lg = $lm("log");
- sn.onclick = function(){
- lg.innerHTML = "";
- var fc = new formChecker(fm,myRule,clear,success,fail,error);
- if (fc.chk() == 0){lg.innerHTML = "All checks are ok";}
- }
- }
- </script>
- </head>
- <body>
- <form id="fm" name="fm" method="post">
- <label for="fnm">Firstname</label><input type="text" name="fnm" id="fnm" class="nm" value="fname" />
- <label for="lnm">Lastname</label><input type="text" name="lnm" id="lnm" class="nm" value="lname" />
- <label for="yr">Age</label><input type="text" name="yr" id="yr" class="yr" value="25" />
- <label for="minyr">Minimum age</label><input type="text" name="minyr" id="minyr" class="minyr" value="18" />
- <label for="maxyr">Maximum age</label><input type="text" name="maxyr" id="maxyr" class="maxyr" value="99" />
- <label for="cn">Country</label><input type="text" name="cn" id="cn" class="cn" value="country (short, i.e. hu or en)" />
- <input type="button" name="send" id="send" value="send" />
- </form>
- <br>
- <div id="log"></log>
- </body>
- </html>
Add Comment
Please, Sign In to add comment