Cool Javascript Validation


/ Published in: JavaScript
Save to your folder(s)

A very easy to use script for validating your forms.


Copy this code and paste it in your HTML
  1. // Online Example At:
  2. // http://www.brainstechnology.com/showreel/validate.html
  3.  
  4. // Save javascript below code as cvalidate.js
  5.  
  6. // Javascript Code Starts
  7. //////////////////////////////////////////////////////////////////
  8. // - COOL VALIDATE v1.00 - //
  9. //////////////////////////////////////////////////////////////////
  10. // Developed By ; //
  11. // SARFRAZ AHMED CHANDIO //
  12. // //
  13. // http://www.brainstechnology.com //
  14. // //
  15. // 01 Feb 2009 //
  16. //////////////////////////////////////////////////////////////////
  17. // Please keep this notice intact if you are using this file. //
  18. //////////////////////////////////////////////////////////////////
  19.  
  20. /*
  21. ?? Future Additions ?? (--) & Fixes (-):
  22. ========================================
  23. -- Custom RegEX
  24. -- God Knows !!
  25. */
  26.  
  27.  
  28. // cross-browser document.getElementById, should be on top of code.
  29. if(!document.getElementById)
  30. {
  31. if(document.all)
  32. document.getElementById=function()
  33. {
  34. if(typeof document.all[arguments[0]]!="undefined")
  35. return document.all[arguments[0]]
  36. else
  37. return null
  38. }
  39. else if(document.layers)
  40. document.getElementById=function()
  41. {
  42. if(typeof document[arguments[0]]!="undefined")
  43. return document[arguments[0]]
  44. else
  45. return null
  46. }
  47. }
  48. ////////////////////////////////////////////////
  49.  
  50. function trimAll(sString)
  51. {
  52. while (sString.substring(0,1) == ' ')
  53. {
  54. sString = sString.substring(1, sString.length);
  55. }
  56. while (sString.substring(sString.length-1, sString.length) == ' ')
  57. {
  58. sString = sString.substring(0,sString.length-1);
  59. }
  60. return sString;
  61. }
  62.  
  63. function validateForm(formid)
  64. {
  65. // regex patterns, more can be added
  66. var pattern_email = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
  67. var pattern_date = /^\d\d\/\d\d\/\d\d\d\d$/;
  68. var pattern_number = /^\-?\d+$/;
  69. var pattern_text = /^[a-zA-Z ]+$/;
  70. var pattern_alpha = /^\w+$/;
  71. var pattern_decimal = /^\-?\d+(\.\d+)?$/;
  72. var pattern_web = /^https?\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?$/;
  73. ////////////////////////////////////////////////
  74.  
  75. var formobj = document.forms[formid];
  76. var arr_vtype = new Array();
  77. var fieldname = "";
  78. var vtype = "";
  79. var counter = 0;
  80. var fieldtype = "";
  81. var fieldvalue = "";
  82. var fieldtitle = "";
  83. var curfield = "";
  84. var emsg = "";
  85.  
  86. for (var i=0; i<formobj.elements.length; i++)
  87. {
  88. arr_vtype = formobj.elements[i].className.split(" ");
  89.  
  90. // If this is the field to be validated
  91. if (arr_vtype[0] == "required")
  92. {
  93. counter++; // total fields to be validated
  94.  
  95. // get current field
  96. curfield = formobj.elements[i];
  97. // get field type
  98. fieldtype = formobj.elements[i].type;
  99.  
  100. // get field name
  101. if (formobj.elements[i].getAttribute("name"))
  102. {
  103. fieldname = formobj.elements[i].getAttribute("name");
  104. }
  105.  
  106. // get field title
  107. if (formobj.elements[i].getAttribute("title"))
  108. {
  109. fieldtitle = formobj.elements[i].getAttribute("title");
  110. }
  111.  
  112. if (!fieldtitle)
  113. {
  114. fieldtitle = fieldname;
  115. }
  116.  
  117. // get current filed value
  118. fieldvalue = formobj.elements[i].value;
  119. // get validation type
  120. vtype = arr_vtype[1];
  121.  
  122. // get validation stuff from class tag irrespective of their order
  123. for (var z = 0; z < 10; z++)
  124. {
  125. if (arr_vtype[z] == "min")
  126. {
  127. var cmin = arr_vtype[parseInt(z, 10) + 1];
  128. }
  129. else if (arr_vtype[z] == "max")
  130. {
  131. var cmax = arr_vtype[parseInt(z, 10) + 1];
  132. }
  133. else if (arr_vtype[z] == "match")
  134. {
  135. var comparefield = arr_vtype[parseInt(z, 10) + 1];
  136. var pvalue = fieldvalue;
  137. var ptitle = fieldtitle;
  138. var pfield = curfield;
  139. }
  140. }
  141.  
  142. // for comparing password and confirm passwords
  143. if (comparefield != "" && fieldname == comparefield)
  144. {
  145. var cpvalue = fieldvalue;
  146. var cptitle = fieldtitle;
  147.  
  148. if (trimAll(pvalue) != "" && trimAll(cpvalue) != "")
  149. {
  150. if (pvalue.length < cmin && cmin > 0 && pfield.className.indexOf("min") > -1)
  151. {
  152. pfield.style.borderColor = "#FF0000";
  153. emsg += "--> " + ptitle + " - should be at least " + cmin + " characters long\n";
  154. }
  155. else if (pvalue.length > cmax && cmax > 0 && pfield.className.indexOf("max") > -1)
  156. {
  157. pfield.style.borderColor = "#FF0000";
  158. emsg += "--> " + ptitle + " - should be at most " + cmax + " characters long\n";
  159. }
  160. else if (pvalue != cpvalue)
  161. {
  162. pfield.style.borderColor = "#FF0000";
  163. emsg += "--> " + ptitle + " - and " + cptitle + " must MATCH\n";
  164. }
  165. else
  166. {
  167. pfield.style.borderColor = "#00FF00";
  168. }
  169. }
  170. }
  171. ////////////////////////////////////////////
  172.  
  173. // Do the validation stuff now
  174. switch (vtype)
  175. {
  176. case "alpha":
  177. if (trimAll(fieldvalue) == "")
  178. {
  179. curfield.style.borderColor = "#FF0000";
  180. emsg += "--> " + fieldtitle + " - REQUIRED\n";
  181. }
  182. else if (!pattern_alpha.test(fieldvalue))
  183. {
  184. curfield.style.borderColor = "#FF0000";
  185. emsg += "--> " + fieldtitle + " - should be ALPHA characters\n";
  186. }
  187. else
  188. {
  189. curfield.style.borderColor = "#00FF00";
  190. }
  191. break;
  192. case "text":
  193. if (trimAll(fieldvalue) == "")
  194. {
  195. curfield.style.borderColor = "#FF0000";
  196. emsg += "--> " + fieldtitle + " - REQUIRED\n";
  197. }
  198. else if (!pattern_text.test(fieldvalue))
  199. {
  200. curfield.style.borderColor = "#FF0000";
  201. emsg += "--> " + fieldtitle + " - should only contain A-Z characters\n";
  202. }
  203. else
  204. {
  205. curfield.style.borderColor = "#00FF00";
  206. }
  207. break;
  208. case "email":
  209. if (trimAll(fieldvalue) == "")
  210. {
  211. curfield.style.borderColor = "#FF0000";
  212. emsg += "--> " + fieldtitle + " - REQUIRED\n";
  213. }
  214. else if (!pattern_email.test(fieldvalue))
  215. {
  216. curfield.style.borderColor = "#FF0000";
  217. emsg += "--> " + fieldtitle + " - should be in valid EMAIL format\n";
  218. }
  219. else
  220. {
  221. curfield.style.borderColor = "#00FF00";
  222. }
  223. break;
  224. case "date":
  225. if (trimAll(fieldvalue) == "")
  226. {
  227. curfield.style.borderColor = "#FF0000";
  228. emsg += "--> " + fieldtitle + " - REQUIRED\n";
  229. }
  230. else if (!pattern_date.test(fieldvalue))
  231. {
  232. curfield.style.borderColor = "#FF0000";
  233. emsg += "--> " + fieldtitle + " - should be in DD/MM/YYYY format\n";
  234. }
  235. else
  236. {
  237. curfield.style.borderColor = "#00FF00";
  238. }
  239. break;
  240. case "number":
  241. if (trimAll(fieldvalue) == "")
  242. {
  243. curfield.style.borderColor = "#FF0000";
  244. emsg += "--> " + fieldtitle + " - REQUIRED\n";
  245. }
  246. else if (!pattern_number.test(fieldvalue))
  247. {
  248. curfield.style.borderColor = "#FF0000";
  249. emsg += "--> " + fieldtitle + " - should contain only NUMBERS\n";
  250. }
  251. // since this is number, we compare them directly rather than their length
  252. else if (parseInt(fieldvalue, 10) < parseInt(cmin, 10) && parseInt(cmin, 10) > 0 && curfield.className.indexOf("min") > -1)
  253. {
  254. curfield.style.borderColor = "#FF0000";
  255. emsg += "--> " + fieldtitle + " - should be at least " + cmin + "\n";
  256. }
  257. else if (parseInt(fieldvalue, 10) > parseInt(cmax, 10) && parseInt(cmax, 10) > 0 && curfield.className.indexOf("max") > -1)
  258. {
  259. curfield.style.borderColor = "#FF0000";
  260. emsg += "--> " + fieldtitle + " - should be at most " + cmax + "\n";
  261. }
  262. else
  263. {
  264. curfield.style.borderColor = "#00FF00";
  265. }
  266. break;
  267. case "decimal":
  268. if (trimAll(fieldvalue) == "")
  269. {
  270. curfield.style.borderColor = "#FF0000";
  271. emsg += "--> " + fieldtitle + " - REQUIRED\n";
  272. }
  273. else if (!pattern_decimal.test(fieldvalue))
  274. {
  275. curfield.style.borderColor = "#FF0000";
  276. emsg += "--> " + fieldtitle + " - should contain only DECIMAL NUMBER\n";
  277. }
  278. // since this is number, we compare them directly rather than their length
  279. else if (parseFloat(fieldvalue) < parseFloat(cmin) && parseFloat(cmin) > 0 && curfield.className.indexOf("min") > -1)
  280. {
  281. curfield.style.borderColor = "#FF0000";
  282. emsg += "--> " + fieldtitle + " - should be at least " + cmin + "\n";
  283. }
  284. else if (parseFloat(fieldvalue) > parseFloat(cmax) && parseFloat(cmax) > 0 && curfield.className.indexOf("max") > -1)
  285. {
  286. curfield.style.borderColor = "#FF0000";
  287. emsg += "--> " + fieldtitle + " - should be at most " + cmax + "\n";
  288. }
  289. else
  290. {
  291. curfield.style.borderColor = "#00FF00";
  292. }
  293. break;
  294. case "web":
  295. if (trimAll(fieldvalue) == "")
  296. {
  297. curfield.style.borderColor = "#FF0000";
  298. emsg += "--> " + fieldtitle + " - REQUIRED\n";
  299. }
  300. else if (!pattern_web.test(fieldvalue))
  301. {
  302. curfield.style.borderColor = "#FF0000";
  303. emsg += "--> " + fieldtitle + " - should be in URL format\n";
  304. }
  305. else
  306. {
  307. curfield.style.borderColor = "#00FF00";
  308. }
  309. break;
  310. // for fields containing required keyword only
  311. default:
  312. if (fieldtype == "checkbox")
  313. {
  314. if (!curfield.checked)
  315. {
  316. emsg += "--> " + fieldtitle + " - REQUIRED\n";
  317. }
  318. }
  319. else
  320. {
  321. if (trimAll(fieldvalue) == "")
  322. {
  323. curfield.style.borderColor = "#FF0000";
  324. emsg += "--> " + fieldtitle + " - REQUIRED\n";
  325. }
  326. else
  327. {
  328. if (fieldtype != "radio")
  329. {
  330. curfield.style.borderColor = "#00FF00";
  331. }
  332. }
  333. }
  334. break;
  335. }
  336.  
  337. }
  338. }
  339.  
  340. // separetely for radio buttons since many radios can have the same name
  341. var rnames = "";
  342. var rtitles = "";
  343. var radiogroup = new Array();
  344. var arr_titles = new Array();
  345. var msg = "";
  346.  
  347. // Get the radio fields to be validated
  348. for (var j = 0; j < formobj.elements.length; j++)
  349. {
  350. arr_vtype2 = formobj.elements[j].className.split(" ");
  351. if (arr_vtype2[0] == "required")
  352. {
  353. if (formobj.elements[j].type == "radio")
  354. {
  355. if (!formobj.elements[j].checked)
  356. {
  357. if (msg.indexOf(formobj.elements[j].getAttribute("title")) == -1)
  358. {
  359. formobj.elements[j].style.borderColor = "#FF0000";
  360. msg += "--> " + formobj.elements[j].getAttribute("title") + " - REQUIRED\n";
  361. }
  362. }
  363. else if (formobj.elements[j].checked)
  364. {
  365. //msg = msg.replace("--> " + formobj.elements[j].getAttribute("title") + " - REQUIRED\n", "");
  366. rtitles += "|" + formobj.elements[j].getAttribute("title");
  367. rnames += "|" + formobj.elements[j].getAttribute("name");
  368. }
  369. }
  370. }
  371. }
  372.  
  373. radiogroup = rnames.split("|");
  374. arr_titles = rtitles.split("|");
  375.  
  376. // remove checked radio from the msg
  377. for (var p in radiogroup)
  378. {
  379. msg = msg.replace("--> " + arr_titles[p] + " - REQUIRED\n", "");
  380. }
  381.  
  382. if (msg) emsg += msg;
  383. /////////////////////////////////////////
  384.  
  385. if (emsg)
  386. {
  387. var dashes = "----------------------------------------------";
  388. alert ("You failed to correctly fill in your form:\n" + dashes
  389. + "\n" + emsg + dashes + "\nPlease re-enter and submit again!");
  390. return false;
  391. }
  392. else
  393. {
  394. return true;
  395. }
  396. }
  397. // Javascript Code Ends
  398.  
  399.  
  400.  
  401.  
  402. // HTML Form: Save this as validate.html
  403. // put both cvalidate.js and this file in the same folder.
  404.  
  405.  
  406. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  407. <html xmlns="http://www.w3.org/1999/xhtml">
  408. <head>
  409. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  410. <title>CoOl Javascript Validation</title>
  411. <style type="text/css" media="screen">@import "css/basic.css";</style>
  412. <script type="text/javascript" src="cvalidate.js"></script>
  413. <style type="text/css">
  414.  
  415. #dropSheet
  416. {
  417. background-color/**/: #000000;
  418. background-image: url(../images/dots.gif);
  419. background-image/**/: none;
  420. opacity: 0.35;
  421. filter: alpha(opacity=35);
  422. }
  423.  
  424. .heading
  425. {
  426. color:#0099FF;
  427. font-weight:bolder;
  428. font-size:20px;
  429. }
  430. .txt
  431. {
  432. font-family:Verdana, Arial, Helvetica, sans-serif;
  433. font-size:12px;
  434. }
  435. </style>
  436.  
  437. </head>
  438.  
  439. <body>
  440.  
  441. <form name="frmValidate" id="myform" action="" method="post" onsubmit="return validateForm('myform')">
  442. <table width="375" border="0" cellspacing="0" cellpadding="5" align="center" bgcolor="#F4FAFF" style="border:1px solid #0099FF;">
  443. <tr>
  444. <td colspan="2" class="heading" align="center" style="border-bottom:1px solid #0099FF;"> - CoOl Javascript Validation - </td>
  445. </tr>
  446. <tr>
  447. <td colspan="2" class="heading" align="center" height="10"></td>
  448. </tr>
  449.  
  450. <tr>
  451. <td align="left" class="txt">Username *</td>
  452. <td align="left"><input type="text" name="username" id="username" size="28" title="Username" class="required alpha" /></td>
  453. </tr>
  454. <tr>
  455. <td align="left" class="txt">Password *</td>
  456. <td align="left"><input type="password" name="password" id="password" size="28" title="Password" class="required alpha min 6 max 20 match cpassword" /></td>
  457. </tr>
  458. <tr>
  459. <td align="left" class="txt">Confirm Password *</td>
  460. <td align="left"><input type="password" name="cpassword" id="cpassword" size="28" title="Confirm Password" class="required alpha" /></td>
  461. </tr>
  462.  
  463. <tr>
  464. <td align="left" class="txt">First Name *</td>
  465. <td align="left"><input type="text" name="fname" id="fname" size="28" title="First Name" class="required text" /></td>
  466. </tr>
  467. <tr>
  468. <td align="left" class="txt">Last Name</td>
  469. <td align="left"><input type="text" name="lname" id="lname" size="28" title="Last Name" /></td>
  470. </tr>
  471. <tr>
  472. <td align="left" class="txt">Age *</td>
  473. <td align="left"><input type="text" name="age" id="age" size="28" title="Age" class="required number max 100 " /></td>
  474. </tr>
  475. <tr>
  476. <td align="left" class="txt">Email *</td>
  477. <td align="left"><input type="text" name="email" id="email" size="28" title="Email" class="required email" /></td>
  478. </tr>
  479. <tr>
  480. <td align="left" class="txt">Phone *</td>
  481. <td align="left"><input type="text" name="phone" id="phone" size="28" title="Phone" class="required" /></td>
  482. </tr>
  483. <tr>
  484. <td align="left" class="txt">Fax</td>
  485. <td align="left"><input type="text" name="fax" id="fax" size="28" title="Fax" /></td>
  486. </tr>
  487. <tr>
  488. <td align="left" class="txt">Date Of Birth *</td>
  489. <td align="left"><input type="text" name="dob" id="dob" size="28" title="Date Of Birth" class="required date" /></td>
  490. </tr>
  491. <tr>
  492. <td align="left" class="txt">Website *</td>
  493. <td align="left"><input type="text" name="website" id="website" size="28" title="Website" class="required web" /></td>
  494. </tr>
  495. <tr>
  496. <td align="left" class="txt">Country *</td>
  497. <td align="left">
  498. <select name="country" id="country" title="Country" class="required">
  499. <option value="">--- Select ---</option>
  500. <option value="Canada">Canada</option>
  501. <option value="UK">UK</option>
  502. <option value="USA">USA</option>
  503. <option value="Pakistan">Pakistan</option>
  504. <option value="Other">Other</option>
  505. </select>
  506. </td>
  507. </tr>
  508. <tr>
  509. <td align="left" class="txt">Gender *</td>
  510. <td align="left">
  511. <input type="radio" name="gender" value="m" title="Gender" class="required" />Male
  512. <input type="radio" name="gender" value="f" title="Gender" class="required" />Female
  513. </td>
  514. </tr>
  515.  
  516. <tr>
  517. <td align="left" class="txt">Disclaimer *</td>
  518. <td align="left">
  519. <input type="checkbox" name="disclaimer" value="1" title="Disclaimer" class="required" />
  520. </td>
  521. </tr>
  522. <tr>
  523. <td align="right" colspan="2">
  524. <input type="submit" name="btnSubmit" value="Submit Form" />
  525. </td>
  526. </tr>
  527.  
  528. </table>
  529. </form>
  530. <br /><br />
  531.  
  532. <table width="350" border="0" cellspacing="0" cellpadding="5" align="center" bgcolor="#F4FAFF" style="border:1px solid #0099FF;">
  533. <tr>
  534. <td colspan="2" class="heading" align="center" style="border-bottom:1px solid #0099FF;">Using CoOl Validation Script</td>
  535. </tr>
  536. </table>
  537. <br />
  538.  
  539. <div class="txt" style="padding-left:200px; padding-right:200px;">
  540. As the name suggests, the CoOl javascript validation is a piece of javascript code which provides you
  541. with an automated inline form validation using <strong>Document Object Model (DOM)</strong>. The script has built-in
  542. checking of patterns such as <strong>email, date, alpha, text, number, decimal and url</strong>.
  543. So the field you want to apply these patterns to should be a required field first.
  544. <p>
  545. In order to activate the validation for an element, all you have to do is to put the keyword
  546. <strong>required</strong> in the <strong>class attribute</strong> and also set the title of the element
  547. (which will appear in validation box) in the <strong>title attribute</strong>. Finally, just place
  548. <strong>return validateForm('myform')</strong> in the <strong>onSubmit</strong> event of the form
  549. where <strong>myform</strong> is the id of the form being validated.
  550. </p>
  551. <p>
  552. For demonstration, you can have a look at the source code of this page to know how fields are validated.
  553. Please note that the order of the <strong>validation keywords</strong> inside the <strong>class attribute</strong> is crucial, so
  554. if you want to apply your own class from style sheet to style the element, make sure that it comes
  555. after the validation keywords.
  556. </p>
  557. </div>
  558. </body>
  559. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.