/ Published in: JavaScript
A very easy to use script for validating your forms.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// Online Example At: // http://www.brainstechnology.com/showreel/validate.html // Save javascript below code as cvalidate.js // Javascript Code Starts ////////////////////////////////////////////////////////////////// // - COOL VALIDATE v1.00 - // ////////////////////////////////////////////////////////////////// // Developed By ; // // SARFRAZ AHMED CHANDIO // // // // [email protected] // // http://www.brainstechnology.com // // // // 01 Feb 2009 // ////////////////////////////////////////////////////////////////// // Please keep this notice intact if you are using this file. // ////////////////////////////////////////////////////////////////// /* ?? Future Additions ?? (--) & Fixes (-): ======================================== -- Custom RegEX -- God Knows !! */ // cross-browser document.getElementById, should be on top of code. if(!document.getElementById) { if(document.all) document.getElementById=function() { if(typeof document.all[arguments[0]]!="undefined") return document.all[arguments[0]] else return null } else if(document.layers) document.getElementById=function() { if(typeof document[arguments[0]]!="undefined") return document[arguments[0]] else return null } } //////////////////////////////////////////////// function trimAll(sString) { while (sString.substring(0,1) == ' ') { sString = sString.substring(1, sString.length); } while (sString.substring(sString.length-1, sString.length) == ' ') { sString = sString.substring(0,sString.length-1); } return sString; } function validateForm(formid) { // regex patterns, more can be added var pattern_email = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i; var pattern_date = /^\d\d\/\d\d\/\d\d\d\d$/; var pattern_number = /^\-?\d+$/; var pattern_text = /^[a-zA-Z ]+$/; var pattern_alpha = /^\w+$/; var pattern_decimal = /^\-?\d+(\.\d+)?$/; var pattern_web = /^https?\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?$/; //////////////////////////////////////////////// var formobj = document.forms[formid]; var arr_vtype = new Array(); var fieldname = ""; var vtype = ""; var counter = 0; var fieldtype = ""; var fieldvalue = ""; var fieldtitle = ""; var curfield = ""; var emsg = ""; for (var i=0; i<formobj.elements.length; i++) { arr_vtype = formobj.elements[i].className.split(" "); // If this is the field to be validated if (arr_vtype[0] == "required") { counter++; // total fields to be validated // get current field curfield = formobj.elements[i]; // get field type fieldtype = formobj.elements[i].type; // get field name if (formobj.elements[i].getAttribute("name")) { fieldname = formobj.elements[i].getAttribute("name"); } // get field title if (formobj.elements[i].getAttribute("title")) { fieldtitle = formobj.elements[i].getAttribute("title"); } if (!fieldtitle) { fieldtitle = fieldname; } // get current filed value fieldvalue = formobj.elements[i].value; // get validation type vtype = arr_vtype[1]; // get validation stuff from class tag irrespective of their order for (var z = 0; z < 10; z++) { if (arr_vtype[z] == "min") { var cmin = arr_vtype[parseInt(z, 10) + 1]; } else if (arr_vtype[z] == "max") { var cmax = arr_vtype[parseInt(z, 10) + 1]; } else if (arr_vtype[z] == "match") { var comparefield = arr_vtype[parseInt(z, 10) + 1]; var pvalue = fieldvalue; var ptitle = fieldtitle; var pfield = curfield; } } // for comparing password and confirm passwords if (comparefield != "" && fieldname == comparefield) { var cpvalue = fieldvalue; var cptitle = fieldtitle; if (trimAll(pvalue) != "" && trimAll(cpvalue) != "") { if (pvalue.length < cmin && cmin > 0 && pfield.className.indexOf("min") > -1) { pfield.style.borderColor = "#FF0000"; emsg += "--> " + ptitle + " - should be at least " + cmin + " characters long\n"; } else if (pvalue.length > cmax && cmax > 0 && pfield.className.indexOf("max") > -1) { pfield.style.borderColor = "#FF0000"; emsg += "--> " + ptitle + " - should be at most " + cmax + " characters long\n"; } else if (pvalue != cpvalue) { pfield.style.borderColor = "#FF0000"; emsg += "--> " + ptitle + " - and " + cptitle + " must MATCH\n"; } else { pfield.style.borderColor = "#00FF00"; } } } //////////////////////////////////////////// // Do the validation stuff now switch (vtype) { case "alpha": if (trimAll(fieldvalue) == "") { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - REQUIRED\n"; } else if (!pattern_alpha.test(fieldvalue)) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should be ALPHA characters\n"; } else { curfield.style.borderColor = "#00FF00"; } break; case "text": if (trimAll(fieldvalue) == "") { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - REQUIRED\n"; } else if (!pattern_text.test(fieldvalue)) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should only contain A-Z characters\n"; } else { curfield.style.borderColor = "#00FF00"; } break; case "email": if (trimAll(fieldvalue) == "") { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - REQUIRED\n"; } else if (!pattern_email.test(fieldvalue)) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should be in valid EMAIL format\n"; } else { curfield.style.borderColor = "#00FF00"; } break; case "date": if (trimAll(fieldvalue) == "") { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - REQUIRED\n"; } else if (!pattern_date.test(fieldvalue)) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should be in DD/MM/YYYY format\n"; } else { curfield.style.borderColor = "#00FF00"; } break; case "number": if (trimAll(fieldvalue) == "") { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - REQUIRED\n"; } else if (!pattern_number.test(fieldvalue)) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should contain only NUMBERS\n"; } // since this is number, we compare them directly rather than their length else if (parseInt(fieldvalue, 10) < parseInt(cmin, 10) && parseInt(cmin, 10) > 0 && curfield.className.indexOf("min") > -1) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should be at least " + cmin + "\n"; } else if (parseInt(fieldvalue, 10) > parseInt(cmax, 10) && parseInt(cmax, 10) > 0 && curfield.className.indexOf("max") > -1) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should be at most " + cmax + "\n"; } else { curfield.style.borderColor = "#00FF00"; } break; case "decimal": if (trimAll(fieldvalue) == "") { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - REQUIRED\n"; } else if (!pattern_decimal.test(fieldvalue)) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should contain only DECIMAL NUMBER\n"; } // since this is number, we compare them directly rather than their length else if (parseFloat(fieldvalue) < parseFloat(cmin) && parseFloat(cmin) > 0 && curfield.className.indexOf("min") > -1) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should be at least " + cmin + "\n"; } else if (parseFloat(fieldvalue) > parseFloat(cmax) && parseFloat(cmax) > 0 && curfield.className.indexOf("max") > -1) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should be at most " + cmax + "\n"; } else { curfield.style.borderColor = "#00FF00"; } break; case "web": if (trimAll(fieldvalue) == "") { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - REQUIRED\n"; } else if (!pattern_web.test(fieldvalue)) { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - should be in URL format\n"; } else { curfield.style.borderColor = "#00FF00"; } break; // for fields containing required keyword only default: if (fieldtype == "checkbox") { if (!curfield.checked) { emsg += "--> " + fieldtitle + " - REQUIRED\n"; } } else { if (trimAll(fieldvalue) == "") { curfield.style.borderColor = "#FF0000"; emsg += "--> " + fieldtitle + " - REQUIRED\n"; } else { if (fieldtype != "radio") { curfield.style.borderColor = "#00FF00"; } } } break; } } } // separetely for radio buttons since many radios can have the same name var rnames = ""; var rtitles = ""; var radiogroup = new Array(); var arr_titles = new Array(); var msg = ""; // Get the radio fields to be validated for (var j = 0; j < formobj.elements.length; j++) { arr_vtype2 = formobj.elements[j].className.split(" "); if (arr_vtype2[0] == "required") { if (formobj.elements[j].type == "radio") { if (!formobj.elements[j].checked) { if (msg.indexOf(formobj.elements[j].getAttribute("title")) == -1) { formobj.elements[j].style.borderColor = "#FF0000"; msg += "--> " + formobj.elements[j].getAttribute("title") + " - REQUIRED\n"; } } else if (formobj.elements[j].checked) { //msg = msg.replace("--> " + formobj.elements[j].getAttribute("title") + " - REQUIRED\n", ""); rtitles += "|" + formobj.elements[j].getAttribute("title"); rnames += "|" + formobj.elements[j].getAttribute("name"); } } } } radiogroup = rnames.split("|"); arr_titles = rtitles.split("|"); // remove checked radio from the msg for (var p in radiogroup) { msg = msg.replace("--> " + arr_titles[p] + " - REQUIRED\n", ""); } if (msg) emsg += msg; ///////////////////////////////////////// if (emsg) { var dashes = "----------------------------------------------"; alert ("You failed to correctly fill in your form:\n" + dashes + "\n" + emsg + dashes + "\nPlease re-enter and submit again!"); return false; } else { return true; } } // Javascript Code Ends // HTML Form: Save this as validate.html // put both cvalidate.js and this file in the same folder. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>CoOl Javascript Validation</title> <style type="text/css" media="screen">@import "css/basic.css";</style> <script type="text/javascript" src="cvalidate.js"></script> <style type="text/css"> #dropSheet { background-color/**/: #000000; background-image: url(../images/dots.gif); background-image/**/: none; opacity: 0.35; filter: alpha(opacity=35); } .heading { color:#0099FF; font-weight:bolder; font-size:20px; } .txt { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; } </style> </head> <body> <form name="frmValidate" id="myform" action="" method="post" onsubmit="return validateForm('myform')"> <table width="375" border="0" cellspacing="0" cellpadding="5" align="center" bgcolor="#F4FAFF" style="border:1px solid #0099FF;"> <tr> <td colspan="2" class="heading" align="center" style="border-bottom:1px solid #0099FF;"> - CoOl Javascript Validation - </td> </tr> <tr> <td colspan="2" class="heading" align="center" height="10"></td> </tr> <tr> <td align="left" class="txt">Username *</td> <td align="left"><input type="text" name="username" id="username" size="28" title="Username" class="required alpha" /></td> </tr> <tr> <td align="left" class="txt">Password *</td> <td align="left"><input type="password" name="password" id="password" size="28" title="Password" class="required alpha min 6 max 20 match cpassword" /></td> </tr> <tr> <td align="left" class="txt">Confirm Password *</td> <td align="left"><input type="password" name="cpassword" id="cpassword" size="28" title="Confirm Password" class="required alpha" /></td> </tr> <tr> <td align="left" class="txt">First Name *</td> <td align="left"><input type="text" name="fname" id="fname" size="28" title="First Name" class="required text" /></td> </tr> <tr> <td align="left" class="txt">Last Name</td> <td align="left"><input type="text" name="lname" id="lname" size="28" title="Last Name" /></td> </tr> <tr> <td align="left" class="txt">Age *</td> <td align="left"><input type="text" name="age" id="age" size="28" title="Age" class="required number max 100 " /></td> </tr> <tr> <td align="left" class="txt">Email *</td> <td align="left"><input type="text" name="email" id="email" size="28" title="Email" class="required email" /></td> </tr> <tr> <td align="left" class="txt">Phone *</td> <td align="left"><input type="text" name="phone" id="phone" size="28" title="Phone" class="required" /></td> </tr> <tr> <td align="left" class="txt">Fax</td> <td align="left"><input type="text" name="fax" id="fax" size="28" title="Fax" /></td> </tr> <tr> <td align="left" class="txt">Date Of Birth *</td> <td align="left"><input type="text" name="dob" id="dob" size="28" title="Date Of Birth" class="required date" /></td> </tr> <tr> <td align="left" class="txt">Website *</td> <td align="left"><input type="text" name="website" id="website" size="28" title="Website" class="required web" /></td> </tr> <tr> <td align="left" class="txt">Country *</td> <td align="left"> <select name="country" id="country" title="Country" class="required"> <option value="">--- Select ---</option> <option value="Canada">Canada</option> <option value="UK">UK</option> <option value="USA">USA</option> <option value="Pakistan">Pakistan</option> <option value="Other">Other</option> </select> </td> </tr> <tr> <td align="left" class="txt">Gender *</td> <td align="left"> <input type="radio" name="gender" value="m" title="Gender" class="required" />Male <input type="radio" name="gender" value="f" title="Gender" class="required" />Female </td> </tr> <tr> <td align="left" class="txt">Disclaimer *</td> <td align="left"> <input type="checkbox" name="disclaimer" value="1" title="Disclaimer" class="required" /> </td> </tr> <tr> <td align="right" colspan="2"> <input type="submit" name="btnSubmit" value="Submit Form" /> </td> </tr> </table> </form> <br /><br /> <table width="350" border="0" cellspacing="0" cellpadding="5" align="center" bgcolor="#F4FAFF" style="border:1px solid #0099FF;"> <tr> <td colspan="2" class="heading" align="center" style="border-bottom:1px solid #0099FF;">Using CoOl Validation Script</td> </tr> </table> <br /> <div class="txt" style="padding-left:200px; padding-right:200px;"> As the name suggests, the CoOl javascript validation is a piece of javascript code which provides you with an automated inline form validation using <strong>Document Object Model (DOM)</strong>. The script has built-in checking of patterns such as <strong>email, date, alpha, text, number, decimal and url</strong>. So the field you want to apply these patterns to should be a required field first. <p> In order to activate the validation for an element, all you have to do is to put the keyword <strong>required</strong> in the <strong>class attribute</strong> and also set the title of the element (which will appear in validation box) in the <strong>title attribute</strong>. Finally, just place <strong>return validateForm('myform')</strong> in the <strong>onSubmit</strong> event of the form where <strong>myform</strong> is the id of the form being validated. </p> <p> For demonstration, you can have a look at the source code of this page to know how fields are validated. Please note that the order of the <strong>validation keywords</strong> inside the <strong>class attribute</strong> is crucial, so if you want to apply your own class from style sheet to style the element, make sure that it comes after the validation keywords. </p> </div> </body> </html>