Simple Javascript form validation




<html>
<head>
 <title>Test Form</title>
 <style>
  .error{
   border-color: #f00;
  }
 </style>
 <script>
 
  function validateForm(e){ 
   
   var inputType, elem, value;
   var error_list = [];
   var inputs = e.getElementsByTagName('input');
   var error = 0;
   for(var i = 0; i < inputs.length; i++) {
    elem = inputs[i]; 
     
    inputType = elem.getAttribute('type');
    val = elem.value;
    switch(inputType){
     case 'text': 
      if(val == ''){ 
       elem.classList.add('error');
       error_list.push(elem.getAttribute('name'));
      } 
      else{ 
       elem.classList.remove('error');  
       error_list.pop(elem.getAttribute('name'));
      }  
      break;
     case 'password': 
      if(val == ''){ 
       elem.classList.add('error');
       error_list.push(elem.getAttribute('name'));
      } 
      else{ 
       elem.classList.remove('error');  
       error_list.pop(elem.getAttribute('name'));
      }  
      break;
     case 'email':
      if(val == ''){ 
       elem.classList.add('error');
       error_list.push(elem.getAttribute('name'));
      } 
      else if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(val))){
       elem.classList.add('error');
       error_list.push(elem.getAttribute('name'));
      }
      else{ 
       elem.classList.remove('error');  
       error_list.pop(elem.getAttribute('name'));
      } 
      
     break;
     
    }
   } 
   
   if(error_list.length == 0)
    return true;
   else
    return false;
  }
 </script>
</head>
<body>
 
 <form method="GET" action="#" onsubmit="return validateForm(this)">
  <input type="text" name="name" id="name" /> 
  <input type="email" name="email" /> 
  <input type="submit" />  
 </form> 

</body>
</html>





Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.