Posted By

sarfraznawaz2005 on 02/06/09


Tagged

form validation validate


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

atma
beneberle


Cool Javascript Validation


 / Published in: JavaScript
 

A very easy to use script for validating your forms.

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

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: kurokikaze on February 6, 2009

I suppose it should be in JavaScript, not in PHP

You need to login to post a comment.