Posted on Leave a comment

jQuery Baisc Standard Form Validation Script

<div id="status" class="alert alert-danger" style="display:none"></div>
<div class="alert alert-success" style="display:none"></div> 
   
<script>
  function validation()
  {
    
    var firstName = $('#firstName').val();
    var lastName = $('#lastName').val();
    var phone = $('#phone').val();
    var email = $('#email').val();
    var message = $('#message').val();
    
    $(".alert-danger").slideUp();
    
    if((firstName == '') || (lastName == '') || (phone == '') || (email == '') || (message == '') )
    {
      var empty_field_title='';
      if(firstName=='') {empty_field_title='First Name';}
      else if(lastName==''){empty_field_title='Last Name';}
      else if(phone==''){empty_field_title='Phone';}
      else if(email==''){empty_field_title='Email';}
      else if(message==''){empty_field_title='Message';}

      show_error('<strong>Error: </strong>'+empty_field_title+' is required.'); 
      return false; 
    }
    else if(!(/^([a-zA-Z0-9]+[a-zA-Z0-9._%-]*@(?:[a-zA-Z0-9-])+(\.+[a-zA-Z]{2,4}){1,2})$/i.test(email)))
    {
      show_error('<strong>Error: </strong> Email address format is not correct.');
      return false;
    }
    
    
    return true;
      
  }

function show_status(msg, type)
{
	 if(type=="error")
	 {
	  	var status_class=".alert-danger";
	 }
	 else
	 {
	  	var status_class=".alert-success";
	 }

	   $('.alert-danger, .alert-success').slideUp();

	   setTimeout(function(){
	   		$(status_class).html(msg);
	   }, 400);

	   $(status_class).slideDown();
	 
	   // scrolling to the error
	   $('html, body').animate({
	    	scrollTop: $("#status").offset().top
	   }, 2000);
}
  </script>

 

Leave a Reply

Your email address will not be published. Required fields are marked *