prototype - jsvalidate_beta05


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



Copy this code and paste it in your HTML
  1. /* JSValidate preferences */
  2. var js_options = {
  3. errorTag: "span", // which tag do you want to use for error container. it must be one that opens and closes (div,span,p,b)
  4. errorClass: "jsvalidation", // this is the css class name given to the tag above
  5. errorLocation: "afterEnd", // only accepts beforeBegin or afterEnd (either before or after the input element) or none
  6. //note: if you choose "none" for the above attribute, you must create the error yourself and give the element an ID consisting of the option below + the name of the form + the name of the field to validate.
  7. errorIDPrefix: "jsvalidator", // prefix of the id of the element above that will attach to the name or id of the form element. don't use spaces or special characters. unfortunately, this is the only option that cannot be applied individually to each element
  8. startGone: false, //couldn't think of another name for this, but if true, it will apply "display:none", otherwise, the element is just invisible.
  9. useBR: "none", // accepts before, after, both or none; This will add a new line (<br />) before and/or after the above element.
  10. useBlur: true, // this will attach an onBlur validator to each form element.
  11. submitClass: 'submit_action', // apply this class inside any form to let this element submit the form.
  12. resetClass: 'reset_action', // apply this class inside any form to let this element reset the form.
  13. resetConfirm: false, // if true, it will prompt user to confirm if they click a reset button.
  14. highlightColor: '#FFFF99', //default color should be: #FFFF99
  15. endColor: '#FFFFFF', //this is what you generally want to set to the background color behind the form elements.
  16. extMessage: true, // if true, and you have accept value on file input, it tells user what extensions are accepted.
  17. ajaxURL: '/ajaxtest.php' // if not blank, validator will attempt to check value against this URL; if return value is not blank, error container will be populated with return value
  18. }
  19. //note: can apply any of the custom options above by including {optionname: 'value'} in the element's class.
  20.  
  21. //setup validators like: name of validator, default message, /regular expression/ !don't forget the / in front and the / in back!!!!
  22. var custom_validators = {
  23. number: {
  24. className: "jsvalidate_number",
  25. defaultMessage: "This field must have a numerical value.",
  26. regExp: /^[-]?\d+(\.\d+)?$/
  27. },
  28. digits: {
  29. className: "jsvalidate_digits",
  30. defaultMessage: "This field can only contain numbers.",
  31. regExp: /^[-]?\d+(\.\d+)?$/
  32. },
  33. email: {
  34. className: "jsvalidate_email",
  35. defaultMessage: "This field must contain a valid email address.",
  36. regExp: /^([a-zA-Z0-9_\.\-])+(\+[a-zA-Z0-9]+)*\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
  37. },
  38. uscanzip: {
  39. className: "jsvalidate_uscanzip",
  40. defaultMessage: "This field must contain a valid US or Canada zip code.",
  41. regExp: /^((\d{5}([- ])\d{4})|(\d{5})|([AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d[A-Za-z]\s?\d[A-Za-z]\d))$/
  42. },
  43. usstate: {
  44. className: "jsvalidate_usstate",
  45. defaultMessage: "This field must contain a valid 2 letter US state code.",
  46. regExp: /^(A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[ANU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$/
  47. },
  48. usphone: {
  49. className: "jsvalidate_usphone",
  50. defaultMessage: "This field must contain a valid US phone number with area code.",
  51. regExp: /^([0-9]( |-|.)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-|.)?([0-9]{3}( |-|.)?[0-9]{4}|[a-zA-Z0-9]{7})$/
  52. },
  53. creditcard: {
  54. className: "jsvalidate_creditcard",
  55. defaultMessage: "This field must contain a valid credit card number.",
  56. regExp: /^((4\d{3})|(5[1-5]\d{2})|(6011))([- ])?\d{4}([- ])?\d{4}([- ])?\d{4}|3[4,7]\d{13}$/
  57. },
  58. ssn: {
  59. className: "jsvalidate_ssn",
  60. defaultMessage: "This field must contain a valid social security number.",
  61. regExp: /(^|\s)(00[1-9]|0[1-9]0|0[1-9][1-9]|[1-6]\d{2}|7[0-6]\d|77[0-2])(-?|[\. ])([1-9]0|0[1-9]|[1-9][1-9])\3(\d{3}[1-9]|[1-9]\d{3}|\d[1-9]\d{2}|\d{2}[1-9]\d)($|\s|[;:,!\.\?])/
  62. },
  63. alpha: {
  64. className: "jsvalidate_alpha",
  65. defaultMessage: "This field must contain only letters.",
  66. regExp: /^[a-zA-z\s]+$/
  67. },
  68. alphanum: {
  69. className: "jsvalidate_alphanum",
  70. defaultMessage: "This field must contain only letters or numbers.",
  71. regExp: /^[a-zA-Z0-9]+$/
  72. }
  73. };
  74.  
  75.  
  76. /* only change the default message, do not change the className */
  77. var js_validators = {
  78. required: {
  79. className: "jsrequired",
  80. defaultMessage: "This field is required."
  81. },
  82. notfirst: {
  83. className: "select-notfirst",
  84. defaultMessage: "Select something other than the first item."
  85. },
  86. filetypes: {
  87. defaultMessage: "This field accepts the following file types:"
  88. },
  89. ajax: {
  90. className: "ajax",
  91. defaultMessage: "This value should change based on ajax request result."
  92. }
  93. };
  94.  
  95.  
  96. /* begin uneditable code ---- please don't touch */
  97.  
  98.  
  99.  
  100. String.prototype.trim = function() {
  101. a = this.replace(/^\s+/, '');
  102. return a.replace(/\s+$/, '');
  103. };
  104.  
  105. Array.prototype.inArray = function (value){
  106. var i;
  107. for (i=0; i < this.length; i++) {
  108. // Matches identical (===), not just similar (==).
  109. if (this[i] === value) {
  110. return true;
  111. }
  112. }
  113. return false;
  114. };
  115.  
  116. Array.prototype.remove=function(s){
  117. for(i=0;i<this.length;i++){
  118. if(s==this[i]) this.splice(i, 1);
  119. }
  120. };
  121.  
  122. String.prototype.isEmpty = function() {
  123. if ((this.value.length == 0) || (this.value==null)) {
  124. return true;
  125. }
  126. return false;
  127. };
  128.  
  129. // Removes the last element from an array
  130. // and returns that element.
  131. if (!Array.prototype.pop) {
  132. Array.prototype.pop = function() {
  133. var last;
  134. if (this.length) {
  135. last = this[this.length - 1];
  136. this.length -= 1;
  137. }
  138. return last||null;
  139. };
  140. }
  141.  
  142. // Adds one or more elements to the end of an array and returns
  143. // the new length of the array.
  144. if (!Array.prototype.push) {
  145. Array.prototype.push = function() {
  146. for (var i = 0; i < arguments.length; ++i) {
  147. this[this.length] = arguments[i];
  148. }
  149. return this.length;
  150. };
  151. }
  152.  
  153. function isset(v) {
  154. return((typeof(v)=='undefined' || v.length==0) ? false : true);
  155. }
  156.  
  157. function getElementsByClassName(className, tag, elm){
  158. var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
  159. var tag = tag || "*";
  160. var elm = elm || document;
  161. var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
  162. var returnElements = [];
  163. var current;
  164. var length = elements.length;
  165. for(var i=0; i<length; i++){
  166. current = elements[i];
  167. if(testClass.test(current.className)){
  168. returnElements.push(current);
  169. }
  170. }
  171. return returnElements;
  172. }
  173.  
  174. function isArray() {
  175. if (typeof arguments[0] == 'object') {
  176. var criterion = arguments[0].constructor.toString().match(/array/i);
  177. return (criterion != null);
  178. }
  179. return false;
  180. }
  181.  
  182. function isString() {
  183. if (typeof arguments[0] == 'string') return true;
  184. if (typeof arguments[0] == 'object') {
  185. var criterion = arguments[0].constructor.toString().match(/string/i);
  186. return (criterion != null);
  187. }
  188. return false;
  189. }
  190.  
  191.  
  192. function RemoveDuplicates(arr){
  193. if(isArray(arr)){
  194. arr.sort();
  195. returnArray = true;
  196. } else {
  197. returnArray = false;
  198. arr.trim();
  199. arr = arr.split(" ");
  200. arr.sort();
  201. }
  202. var result=new Array();
  203. var lastValue="";
  204. for (var i=0; i<arr.length; i++){
  205. var curValue=arr[i];
  206. if (curValue != lastValue){
  207. result[result.length] = curValue;
  208. }
  209. lastValue = curValue;
  210. }
  211. if(!returnArray){
  212. var newResult = "";
  213. for (var a=0; a < result.length; a++){
  214. newResult += result[a] + " ";
  215. }
  216. newResult.trim();
  217. result = newResult;
  218. }
  219. return result;
  220. }
  221.  
  222.  
  223. function onlyJSV(arr){
  224. if(isArray(arr)){
  225. arr.sort();
  226. returnArray = true;
  227. } else {
  228. returnArray = false;
  229. arr.trim();
  230. arr = arr.split(" ");
  231. arr.sort();
  232. }
  233. var result=new Array();
  234. for (var i=0; i<arr.length; i++){
  235. //see if this matches any of my variables.
  236. for(items in custom_validators){
  237. if(arr[i] == custom_validators[items]['className']){
  238. result[result.length] = arr[i];
  239. }
  240. }
  241. for(items in js_validators){
  242. if(arr[i] == js_validators[items]['className']){
  243. result[result.length] = arr[i];
  244. }
  245. }
  246. }
  247.  
  248. if(!returnArray){
  249. var newResult = "";
  250. for (var a=0; a < result.length; a++){
  251. newResult += result[a] + " ";
  252. }
  253. newResult.trim();
  254. result = newResult;
  255. }
  256. return result;
  257. }
  258.  
  259.  
  260.  
  261. var _emptyTags = {
  262. "IMG": true,
  263. "BR": true,
  264. "INPUT": true,
  265. "META": true,
  266. "LINK": true,
  267. "PARAM": true,
  268. "HR": true
  269. };
  270.  
  271.  
  272. if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentHTML){
  273. HTMLElement.prototype.__defineGetter__("outerHTML", function () {
  274. var attrs = this.attributes;
  275. var str = "<" + this.tagName;
  276. for (var i = 0; i < attrs.length; i++)
  277. str += " " + attrs[i].getAttribute('name') + "=\"" + attrs[i].value + "\"";
  278.  
  279. if (_emptyTags[this.tagName])
  280. return str + ">";
  281.  
  282. return str + ">" + this.innerHTML + "</" + this.tagName + ">";
  283. });
  284.  
  285. HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
  286. var r = this.ownerDocument.createRange();
  287. r.setStartBefore(this);
  288. var df = r.createContextualFragment(sHTML);
  289. this.parentNode.replaceChild(df, this);
  290. });
  291.  
  292.  
  293. HTMLElement.prototype.insertAdjacentHTML = function (sWhere, sHTML) {
  294. var df; // : DocumentFragment
  295. var r = this.ownerDocument.createRange();
  296.  
  297. switch (String(sWhere).toLowerCase()) { // convert to string and unify case
  298. case "beforebegin":
  299. r.setStartBefore(this);
  300. df = r.createContextualFragment(sHTML);
  301. this.parentNode.insertBefore(df, this);
  302. break;
  303.  
  304. case "afterbegin":
  305. r.selectNodeContents(this);
  306. r.collapse(true);
  307. df = r.createContextualFragment(sHTML);
  308. this.insertBefore(df, this.firstChild);
  309. break;
  310.  
  311. case "beforeend":
  312. r.selectNodeContents(this);
  313. r.collapse(false);
  314. df = r.createContextualFragment(sHTML);
  315. this.appendChild(df);
  316. break;
  317.  
  318. case "afterend":
  319. r.setStartAfter(this);
  320. df = r.createContextualFragment(sHTML);
  321. this.parentNode.insertBefore(df, this.nextSibling);
  322. break;
  323. }
  324. };
  325. }
  326.  
  327. var jsValidator = new Array();
  328. var these_options = eval("({})");
  329. var ajaxItems = new Array();
  330. var ajax_pos;
  331. var linkedReset = false;
  332.  
  333. function findForms(){
  334. var forms = document.getElementsByTagName('form');
  335. return forms;
  336. }
  337.  
  338. function getFields(formref,type){
  339. var els;
  340. if(type == "name"){
  341. els = document.forms[formref].elements;
  342. }
  343. if(type == "id"){
  344. els = Form.getElements(formref);
  345. }
  346. return els;
  347. }
  348.  
  349.  
  350. function getParentForm(el){
  351. while(el.parentNode != null && el.tagName != "FORM") el = el.parentNode;
  352. return (el.getAttribute('name')) ? el.getAttribute('name') : el.getAttribute('id');
  353. }
  354.  
  355. function hasLabel(el){
  356. while(el.parentNode != null && el.tagName != "LABEL") el = el.parentNode;
  357. return (el.tagName == "LABEL") ? true : false;
  358. }
  359.  
  360. function getLabel(el){
  361. while(el.parentNode != null && el.tagName != "LABEL") el = el.parentNode;
  362. return el;
  363. }
  364.  
  365.  
  366. function attachSubmit(form_ref){
  367. var form_attach;
  368. var parent_ref;
  369. if(form_ref.cloneNode(false).getAttribute('name') || form_ref.cloneNode(false).getAttribute('id')){
  370. if(document.forms[form_ref.cloneNode(false).getAttribute('name')]){
  371. form_attach = document.forms[eval("form_ref.cloneNode(false).getAttribute('name')")];
  372. form_ref = form_ref.cloneNode(false).getAttribute('name');
  373. } else {
  374. form_attach = $(eval("form_ref.cloneNode(false).getAttribute('id')"));
  375. form_ref = form_ref.cloneNode(false).getAttribute('id');
  376. }
  377. } else {
  378. form_attach = form_ref;
  379. }
  380. if(window.addEventListener){ // Mozilla, Netscape, Firefox
  381. form_attach.onsubmit = function(){ return submitAction(form_ref,'INPUT','submit'); };
  382. } else { // IE
  383. form_attach.attachEvent('onsubmit', function(){ return submitAction(form_ref,'INPUT','submit'); });
  384. }
  385.  
  386. if(window.addEventListener){ // Mozilla, Netscape, Firefox
  387. form_attach.onreset = function(){ return resetAction(form_ref); };
  388. } else { // IE
  389. form_attach.attachEvent('onreset', function(){ return resetAction(form_ref); });
  390. }
  391.  
  392. if(getElementsByClassName(js_options['submitClass']).length > 0){
  393. var buttons = getElementsByClassName(js_options['submitClass']);
  394. for(b=0; b < buttons.length; b++){
  395. parent_ref = getParentForm(buttons[b]);
  396. if(parent_ref == form_ref){
  397. tag = buttons[b].tagName;
  398. if(buttons[b].type){
  399. type = buttons[b].type.toLowerCase();
  400. } else {
  401. type = "";
  402. }
  403. Event.observe(buttons[b], 'click', function(){ return submitAction(form_ref,tag,type); });
  404. }
  405. }
  406. }
  407.  
  408. if(getElementsByClassName(js_options['resetClass']).length > 0){
  409. var buttons = getElementsByClassName(js_options['resetClass']);
  410. for(r=0; r < buttons.length; r++){
  411. parent_ref = getParentForm(buttons[r]);
  412. if(parent_ref == form_ref){
  413. Event.observe(buttons[r], 'click', function(){ linkedReset = true; document.forms[form_ref].reset(); return false; });
  414. }
  415. }
  416. }
  417. }
  418.  
  419. function extractOptions(vals){
  420. var first_pos = vals.indexOf("{");
  421. var last_pos = vals.indexOf("}") + 1;
  422. var the_options = vals.substring(first_pos,last_pos);
  423. return the_options;
  424. }
  425.  
  426. var radioNum = 0;
  427. function attachValidation(fieldref,form_name){
  428. var validation_message = "";
  429. var the_field;
  430. var these_options = eval("({})");
  431. var isRadio = false;
  432. var doneRadios = new Array();
  433. var doExt = true;
  434. var useBlur = false;
  435. if(document.forms[form_name].elements[fieldref]){
  436. the_field = document.forms[form_name].elements[fieldref];
  437. if(typeof the_field.nodeType == "undefined"){
  438. el_type = the_field[0].type.toLowerCase();
  439. } else {
  440. el_type = the_field.type.toLowerCase();
  441. }
  442. if(el_type == "radio"){
  443. isRadio = true;
  444. }
  445. } else {
  446. the_field = $(fieldref);
  447. }
  448.  
  449. if(isRadio){
  450. classes = "";
  451. for(r=0; r < the_field.length; r++){
  452. classes += the_field[r].className + " ";
  453. }
  454. } else {
  455. classes = the_field.className;
  456. }
  457. if(classes){
  458. if(classes.indexOf("{") > -1 && classes.indexOf("}") > -1){
  459. these_options = extractOptions(classes).toString();
  460. classes = classes.replace(these_options,"");
  461. these_options = eval("(" + these_options + ")");
  462. }
  463. useBlur = (isset(these_options['useBlur'])) ? these_options['useBlur'] : js_options['useBlur'];
  464. extMessage = (isset(these_options['extMessage'])) ? these_options['extMessage'] : js_options['extMessage'];
  465.  
  466. classes.trim();
  467. classes = RemoveDuplicates(classes);
  468. classes = onlyJSV(classes);
  469. classes = classes.trim();
  470. classList = classes.split(" ");
  471.  
  472. for(c=0; c < classList.length; c++){
  473. for(items in js_validators){
  474. if(classList[c] == js_validators[items]['className']){
  475. if(validation_message == ""){
  476. validation_message = js_validators[items]['defaultMessage'];
  477. } else {
  478. validation_message += ' ' + js_validators[items]['defaultMessage'];
  479. }
  480. if(!jsValidator.inArray(fieldref + "," + form_name + "," + the_field.className)){
  481. array_pos = jsValidator.length;
  482. jsValidator[array_pos] = fieldref + "," + form_name + "," + the_field.className;
  483. }
  484. }
  485. }
  486.  
  487. for(items in custom_validators){
  488. if(classList[c] == custom_validators[items]['className']){
  489. if(validation_message == ""){
  490. validation_message = custom_validators[items]['defaultMessage'];
  491. } else {
  492. validation_message += ' ' + custom_validators[items]['defaultMessage'];
  493. }
  494. if(!jsValidator.inArray(fieldref + "," + form_name + "," + the_field.className)){
  495. array_pos = jsValidator.length;
  496. jsValidator[array_pos] = fieldref + "," + form_name + "," + the_field.className;
  497. }
  498. }
  499. }
  500.  
  501. if(isRadio){
  502. for(n=0; n < the_field.length; n++){
  503. if(the_field[n].getAttribute('alt') != "" && the_field[n].getAttribute('alt') != null){
  504. validation_message = the_field[n].getAttribute('alt');
  505. }
  506. }
  507. } else {
  508. if(the_field.getAttribute('alt')){
  509. if(the_field.getAttribute('alt') != "" && the_field.getAttribute('alt') != null){
  510. validation_message = the_field.getAttribute('alt');
  511. }
  512. }
  513. }
  514.  
  515. if(el_type == "file" && extMessage && doExt){
  516. if(the_field.getAttribute('accept') != ""){
  517. if(validation_message == ""){
  518. validation_message = js_validators['filetypes']['defaultMessage'] + " " + the_field.getAttribute('accept');
  519. } else {
  520. validation_message += " " + js_validators['filetypes']['defaultMessage'] + " " + the_field.getAttribute('accept');
  521. }
  522. }
  523. doExt = false;
  524. }
  525. }
  526. }
  527.  
  528. if(validation_message != "" && validation_message != null){
  529. errorTag = (isset(these_options['errorTag'])) ? these_options['errorTag'] : js_options['errorTag'];
  530. errorClass = (isset(these_options['errorClass'])) ? these_options['errorClass'] : js_options['errorClass'];
  531. startGone = (isset(these_options['startGone'])) ? these_options['startGone'] : js_options['startGone'];
  532. useBR = (isset(these_options['useBR'])) ? these_options['useBR'] : js_options['useBR'];
  533. errorLocation = (isset(these_options['errorLocation'])) ? these_options['errorLocation'] : js_options['errorLocation'];
  534.  
  535. var field_name = js_options['errorIDPrefix'] + "_" + form_name + "_" + fieldref;
  536. field_name = field_name.trim();
  537.  
  538. var html = "<";
  539.  
  540. html += errorTag;
  541. html += " id=\"" + field_name + "\" ";
  542. if(errorClass != ""){
  543. html += "class=\"" + errorClass + "\" ";
  544. }
  545. html += "style=\"opacity:0; filter:alpha(opacity=0);";
  546. if(startGone){
  547. html += " display:none;";
  548. }
  549. html += "\">";
  550. if(useBR != "none"){
  551. if(useBR == "before" || useBR == "both"){
  552. html += '<br />';
  553. }
  554. }
  555. html += validation_message;
  556. if(useBR != "none"){
  557. if(useBR == "after" || useBR == "both"){
  558. html += '<br />';
  559. }
  560. }
  561.  
  562. html += "</";
  563. html += errorTag;
  564. html += ">";
  565.  
  566. if(errorLocation == "afterEnd" || errorLocation == "beforeBegin"){
  567. if(isRadio){
  568. if(errorLocation == "afterEnd"){
  569. totalRadios = the_field.length - 1;
  570. if(radioNum == totalRadios){
  571. addTo = (hasLabel(the_field[radioNum])) ? getLabel(the_field[radioNum]) : the_field[radioNum];
  572. addTo.insertAdjacentHTML(errorLocation,html);
  573. radio_pos = doneRadios.length;
  574. doneRadios[radio_pos] = the_field[radioNum].getAttribute('name');
  575. }
  576. radioNum++;
  577. } else {
  578. if(!doneRadios.inArray(the_field[0].getAttribute('name'))){
  579. the_field[0].insertAdjacentHTML(errorLocation,html);
  580. radio_pos = doneRadios.length;
  581. doneRadios[radio_pos] = the_field[radioNum].getAttribute('name');
  582. }
  583. }
  584. } else {
  585. this_type = the_field.type.toLowerCase();
  586. if(this_type == "checkbox"){
  587. attachTo = (hasLabel(the_field)) ? getLabel(the_field) : the_field;
  588. attachTo.insertAdjacentHTML(errorLocation,html);
  589. } else {
  590. the_field.insertAdjacentHTML(errorLocation,html);
  591. }
  592. }
  593. }
  594. if($(field_name)){
  595. new Effect.Opacity(field_name, {to:0.0, duration: 0 });
  596. }
  597. if(errorLocation == "none" && startGone && $(field_name)){
  598. $(field_name).style.display = 'none';
  599. }
  600. }
  601.  
  602. if(useBlur && classes){
  603. //setup onBlur feature
  604. if(the_field.isArray && the_field[0].type){
  605. field_type = the_field[0].type;
  606. } else {
  607. if(the_field.type){
  608. field_type = the_field.type.toLowerCase();
  609. }
  610. }
  611. if((the_field.tagName == "INPUT" && (field_type == "text" || field_type == "password")) || the_field.tagName == "TEXTAREA"){
  612. Event.observe(the_field, 'blur', function(){ blurAction(the_field,form_name); });
  613. }
  614. if(the_field.tagName == "SELECT"){
  615. Event.observe(the_field, 'blur', function(){ blurAction(the_field,form_name); });
  616. Event.observe(the_field, 'change', function(){ blurAction(the_field,form_name); });
  617. }
  618. if(the_field.tagName == "INPUT" && field_type == "checkbox"){
  619. Event.observe(the_field, 'click', function(){ blurAction(the_field,form_name); });
  620. }
  621. if(the_field.tagName == "INPUT" && field_type == "checkbox"){
  622. Event.observe(the_field, 'blur', function(){ blurAction(the_field,form_name); });
  623. Event.observe(the_field, 'click', function(){ blurAction(the_field,form_name); });
  624. Event.observe(the_field, 'change', function(){ blurAction(the_field,form_name); });
  625. }
  626. if(typeof the_field.nodeType == "undefined"){
  627. for(a=0; a < the_field.length; a++){
  628. if(!radio_name){
  629. var radio_name = the_field[a].getAttribute('name');
  630. }
  631. Event.observe(document.forms[form_name].elements[radio_name][a], 'click', function(){ blurAction(the_field,form_name); });
  632. }
  633. }
  634. }
  635. }
  636.  
  637. function getFileExtension(filename){
  638. if( filename.length == 0 ) return "";
  639. var dot = filename.lastIndexOf(".");
  640. if( dot == -1 ) return "";
  641. var extension = filename.substr(dot + 1,filename.length);
  642. return extension;
  643. }
  644.  
  645. function blurAction(field_reference,form_ref){
  646. var field_name;
  647. var the_result = true;
  648. var these_options = eval("({})");
  649. var isRadio = false;
  650. var isDisabled = false;
  651.  
  652. if(($(field_reference)) || (document.forms[form_ref].elements[field_reference])){
  653. field_reference = ($(field_reference)) ? $(field_reference) : document.forms[form_ref].elements[field_reference];
  654. }
  655.  
  656. if(typeof field_reference.nodeType == "undefined"){
  657. the_field = (field_reference[0].getAttribute('name')) ? field_reference[0].getAttribute('name') : field_reference[0].getAttribute('id');
  658. isRadio = true;
  659. } else {
  660. the_field = (field_reference.getAttribute('id')) ? field_reference.getAttribute('id') : field_reference.getAttribute('name');
  661. }
  662.  
  663. if(isRadio){
  664. classes = "";
  665. for(r=0; r < field_reference.length; r++){
  666. classes += field_reference[r].className + " ";
  667. }
  668. } else {
  669. classes = field_reference.className;
  670. }
  671. if(!isRadio){
  672. isDisabled = field_reference.disabled;
  673. }
  674. if(classes && !isDisabled){
  675. if(classes.indexOf("{") > -1 && classes.indexOf("}") > -1){
  676. these_options = extractOptions(classes);
  677. classes = classes.replace(these_options,"");
  678. these_options = eval("(" + these_options + ")");
  679. }
  680. classes = classes.trim();
  681. classes = RemoveDuplicates(classes);
  682. classes = onlyJSV(classes);
  683. classes = classes.trim();
  684. classList = classes.split(" ");
  685. var bad_field = false;
  686. var isRequired = false;
  687. var isAjax = false;
  688.  
  689. hColor = (isset(these_options['highlightColor'])) ? these_options['highlightColor'] : js_options['highlightColor'];
  690. eColor = (isset(these_options['endColor'])) ? these_options['endColor'] : js_options['endColor'];
  691. startGone = (isset(these_options['startGone'])) ? these_options['startGone'] : js_options['startGone'];
  692. errorLocation = (isset(these_options['errorLocation'])) ? these_options['errorLocation'] : js_options['errorLocation'];
  693. ajaxURL = (isset(these_options['ajaxURL'])) ? these_options['ajaxURL'] : js_options['ajaxURL'];
  694.  
  695. for(c=0; c < classList.length; c++){
  696. field_name = js_options['errorIDPrefix'] + "_" + form_name + "_" + the_field;
  697. field_name = field_name.trim();
  698.  
  699. for(items in custom_validators){
  700. if(classList[c] == custom_validators[items]['className'] && field_reference.value != ""){
  701. var thisRegExp = custom_validators[items]['regExp'];
  702. if(!thisRegExp.test(field_reference.value)){
  703. bad_field = true;
  704. }
  705. }
  706. }
  707.  
  708. if(classList[c] == js_validators['required']['className']){
  709. isRequired = true;
  710. if(typeof field_reference.nodeType == "undefined"){
  711. thistype = field_reference[0].type.toLowerCase();
  712. field_type = thistype;
  713. thisTag = field_reference[0].tagName;
  714. } else {
  715. field_type = field_reference.type.toLowerCase();
  716. thisTag = field_reference.tagName;
  717. }
  718. if((thisTag == "INPUT" && (field_type == "text" || field_type == "password")) || thisTag == "TEXTAREA"){
  719. if(field_reference.value == ""){
  720. bad_field = true;
  721. }
  722. }
  723. if(thisTag == "SELECT"){
  724. if(field_reference.value == ""){
  725. bad_field = true;
  726. }
  727. }
  728. if(thisTag == "INPUT" && field_type == "checkbox"){
  729. if(field_reference.checked == false){
  730. bad_field = true;
  731. }
  732. }
  733. if(thisTag == "INPUT" && field_type == "file"){
  734. if(field_reference.value == ""){
  735. bad_field = true;
  736. } else {
  737. if(field_reference.getAttribute('accept') != ""){
  738. pass = false;
  739. fileTypes = field_reference.getAttribute('accept').split(",");
  740. ext = getFileExtension(field_reference.value)
  741. for(f=0; f < fileTypes.length; f++){
  742. if(ext == fileTypes[f]){
  743. pass = true;
  744. }
  745. }
  746. if(!pass){
  747. bad_field = true;
  748. }
  749. }
  750. }
  751. }
  752.  
  753. if(thisTag == "INPUT" && field_type == "radio"){
  754. this_field = (field_reference.name) ? document.forms[form_ref].elements[field_reference.name] : document.forms[form_ref].elements[field_reference[0].name];
  755. theRadios = this_field.length;
  756. bad_field = true;
  757. for(t=0; t < theRadios; t++){
  758. if(this_field[t].checked == true){
  759. bad_field = false;
  760. }
  761. }
  762. }
  763. }
  764.  
  765. if(classList[c] == js_validators['notfirst']['className']){
  766. if(field_reference.selectedIndex == 0 && field_reference.tagName == "SELECT"){
  767. bad_field = true;
  768. }
  769. }
  770.  
  771. if(classList[c] == js_validators['ajax']['className']){
  772. isAjax = true;
  773. }
  774. }
  775.  
  776. if(isAjax){
  777. if(isRequired && field_reference.value == ""){
  778. //reset required message
  779. replaceHTML = js_validators['required']['defaultMessage'];
  780. if(field_reference.getAttribute('alt')){
  781. if(field_reference.getAttribute('alt') != "" && field_reference.getAttribute('alt') != null){
  782. replaceHTML = field_reference.getAttribute('alt');
  783. }
  784. }
  785. Element.update(field_name, replaceHTML);
  786. } else {
  787. if(ajaxURL){
  788. bad_field = false;
  789. ajaxArea = field_name;
  790. if(!ajaxItems.inArray(ajaxArea)){
  791. ajax_pos = ajaxItems.length;
  792. ajaxItems[ajax_pos] = ajaxArea;
  793. }
  794. poststr = the_field + "=" + encodeURIComponent(field_reference.value);
  795. new Ajax.Request(ajaxURL, { parameters: poststr, onSuccess: function(t){
  796. response = t.responseText.trim()
  797. if(response != ""){
  798. Element.update(ajaxArea, response);
  799. throwFlag(ajaxArea,hColor,eColor,startGone);
  800. } else {
  801. if(field_reference.value != ""){
  802. hideFlag(ajaxArea,startGone);
  803. }
  804. ajaxItems.remove(ajaxArea);
  805. }
  806. }
  807. });
  808. }
  809. }
  810. }
  811.  
  812. if(bad_field){
  813. if(errorLocation == "none"){
  814. if($(field_name)){
  815. throwFlag(field_name, hColor, eColor,startGone);
  816. }
  817. } else {
  818. throwFlag(field_name, hColor, eColor,startGone);
  819. }
  820. the_result = false;
  821. } else {
  822. if(errorLocation == "none"){
  823. if($(field_name)){
  824. hideFlag(field_name,startGone);
  825. }
  826. } else {
  827. hideFlag(field_name,startGone);
  828. }
  829. }
  830. }
  831.  
  832. return the_result;
  833. }
  834.  
  835.  
  836. function validTag(theTag){
  837. if(theTag == "INPUT" || theTag == "SELECT" || theTag == "TEXTAREA" || theTag == "BUTTON" || theTag == "ISINDEX"){
  838. return true;
  839. }
  840. return false;
  841. }
  842.  
  843. function checkJSVForm(form_obj){
  844. var isRadio = false;
  845. form_name = form_obj.cloneNode(false).getAttribute('name');
  846. if(form_name){
  847. fields = getFields(form_name,"name");
  848. } else {
  849. fields = getFields(form_obj.getAttribute('id'),"id");
  850. }
  851.  
  852. for(f=0; f < fields.length; f++){
  853. if(document.forms[form_name].elements[fields[f]]){
  854. the_field = document.forms[form_name].elements[fields[f]];
  855. if(typeof the_field.nodeType == "undefined"){
  856. el_type = the_field[0].type.toLowerCase();
  857. } else {
  858. el_type = the_field.type.toLowerCase();
  859. }
  860. if(el_type == "radio"){
  861. isRadio = true;
  862. }
  863. } else {
  864. the_field = $(fields[f]);
  865. }
  866.  
  867. if(isRadio){
  868. classes = "";
  869. for(r=0; r < the_field.length; r++){
  870. classes += the_field[r].className + " ";
  871. }
  872. } else {
  873. classes = the_field.className;
  874. }
  875. if(classes){
  876. if(classes.indexOf("{") > -1 && classes.indexOf("}") > -1){
  877. these_options = extractOptions(classes).toString();
  878. classes = classes.replace(these_options,"");
  879. these_options = eval("(" + these_options + ")");
  880. }
  881. useBlur = (isset(these_options['useBlur'])) ? these_options['useBlur'] : js_options['useBlur'];
  882. extMessage = (isset(these_options['extMessage'])) ? these_options['extMessage'] : js_options['extMessage'];
  883.  
  884. classes.trim();
  885. classes = RemoveDuplicates(classes);
  886. classes = onlyJSV(classes);
  887. classes = classes.trim();
  888. if(classes){
  889. return true;
  890. }
  891. }
  892. }
  893. return false;
  894. }
  895.  
  896. function loadAction(){
  897. var forms = findForms();
  898. var attachIt;
  899. var fields;
  900. var j;
  901. var done;
  902. if(forms.length >= 1){
  903. for(var i=0; i < forms.length; i++){
  904. doValidate = checkJSVForm(forms[i]);
  905. if(doValidate){
  906. attachIt = attachSubmit(forms[i]);
  907. form_name = forms[i].cloneNode(false).getAttribute('name');
  908. if(form_name){
  909. fields = getFields(form_name,"name");
  910. } else {
  911. fields = getFields(forms[i].getAttribute('id'),"id");
  912. }
  913. for(j=0; j < fields.length; j++){
  914. done = false;
  915. if(fields[j].getAttribute('id') && validTag(fields[j].tagName)){
  916. attachValidation(fields[j].getAttribute('id'),form_name);
  917. done = true;
  918. }
  919. if(fields[j].getAttribute('name') && done == false && validTag(fields[j].tagName)){
  920. attachValidation(fields[j].getAttribute('name'),form_name);
  921. done = true;
  922. }
  923. }
  924. }
  925. }
  926. }
  927. }
  928.  
  929.  
  930. function throwFlag(fieldToFlag, hColor, eColor, gone){
  931. if(Element.getOpacity(fieldToFlag) > .75){
  932. new Effect.Highlight(fieldToFlag,{duration:1.0, startcolor:hColor, endcolor:eColor });
  933. } else {
  934. if(gone){
  935. $(fieldToFlag).style.display = '';
  936. }
  937. new Effect.Opacity(fieldToFlag, {to:1.0, duration: .5 });
  938. }
  939. }
  940.  
  941. function hideFlag(fieldToHide, gone){
  942. if(Element.getOpacity(fieldToHide) > .25){
  943. new Effect.Opacity(fieldToHide, {to:0.0, duration: .5 });
  944. if(gone){
  945. $(fieldToHide).style.display = 'none';
  946. }
  947. }
  948. }
  949.  
  950.  
  951. function validateFields(theForm){
  952. var the_field;
  953. var proceed = true;
  954.  
  955. for(var jsV=0; jsV < jsValidator.length; jsV++){
  956. var bad_field = false;
  957.  
  958. var els = jsValidator[jsV].split(",");
  959.  
  960. field_ref = els[0];
  961. form_ref = els[1];
  962. class_ref = els[2];
  963.  
  964. if(form_ref == theForm){
  965. checkField = blurAction(field_ref,form_ref);
  966. if(!checkField){
  967. proceed = false;
  968. }
  969. }
  970. }
  971.  
  972. return proceed;
  973. }
  974.  
  975. function resetAction(the_form){
  976. if(js_options['resetConfirm']){
  977. if(!confirm("Are you sure you want to reset this form?")){
  978. return false;
  979. }
  980. }
  981.  
  982. for(var v=0; v < jsValidator.length; v++){
  983. var els = jsValidator[v].split(",");
  984.  
  985. field_ref = els[0];
  986. form_ref = els[1];
  987. class_ref = els[2];
  988.  
  989. if(form_ref == the_form){
  990. hideFlag(js_options['errorIDPrefix'] + "_" + form_name + "_" + field_ref);
  991. }
  992. }
  993. if(linkedReset){
  994. linkedReset = false;
  995. return false;
  996. } else {
  997. return true;
  998. }
  999. }
  1000. function submitAction(thisForm,tag,type){
  1001. var process = validateFields(thisForm);
  1002. if(ajaxItems.length > 0){
  1003. return false;
  1004. }
  1005. if((tag != "INPUT" || (tag == "INPUT" && type != "submit")) && process && (document.forms[thisForm] || $(thisForm))){
  1006. if(document.forms[thisForm]){
  1007. document.forms[thisForm].submit();
  1008. } else {
  1009. $(thisForm).submit();
  1010. }
  1011. return false;
  1012. }
  1013. return process;
  1014. }
  1015.  
  1016.  
  1017. Event.observe(window, 'load', function(){ loadAction(); });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.