Posted By

krisdb on 03/29/07


Tagged

javascript


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

luman
vali29


quick and dirty form validator


 / Published in: JavaScript
 

  1. <form name="frm" id="frm" onsubmit="return validateFrm(this.name,'#fff8dc','Please enter all required fields');">
  2. <input type="text" name="fieldName" id="required" size="20" />
  3. <input type="submit" value="Submit" />
  4. </form>
  5.  
  6. <script language="javascript" type="text/javascript">
  7. function validateFrm(sFrm,sFieldColor,sErrMsg) {
  8. var frm = document.getElementById(sFrm);
  9. var bFailed = false;
  10. var iFocus = -1
  11.  
  12. for (var i=0;i<frm.length;i++) {
  13. if (frm.elements[i].id == 'required')
  14. frm.elements[i].style.background = '#fff';
  15. }
  16.  
  17. for (var i=0;i<frm.length;i++) {
  18. if (frm.elements[i].id == 'required' && frm.elements[i].value == '') {
  19.  
  20. if (iFocus == -1)
  21. iFocus = i;
  22.  
  23. frm.elements[i].style.background = sFieldColor;
  24. bFailed = true;
  25. }
  26.  
  27. }
  28.  
  29. if (bFailed == true) {
  30. frm.elements[iFocus].focus();
  31. alert(sErrMsg);
  32. return false;
  33. }
  34. }
  35. </script>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: krisdb on March 30, 2007

You need to login to post a comment.