HOME / BLOG / BLOG-POST

How to validate a form using jquery?

Validate a form using jquery

//contact form validation jquery code
 $(".contact-submit").click(function(e){
  
  //e.preventDefault();
  
  var firstname = $(".contact-firstname").val();
  var lastname = $(".contact-lastname").val();
  var email = $(".contact-email").val();
  var phone = $(".contact-phone").val();
  var message = $(".contact-message").val();
  
  
  if(firstname == ""){
   $(".contact-firstname").focus();
   $(".first-i").html("Please input firstname here");
   return false;
  }
  
  
  if(lastname == ""){
   $(".contact-lastname").focus();
   $(".contact-lastname").after("<i>Please input lastname here</i>")
   return false;
  }
  
  if(email == ""){
   $(".contact-email").focus();
   $(".contact-email").after("<i>Please input email here</i>")
   return false;
  }
  
 });
 
 $("input[type='text']").click(function(){
  $("i").html("");
 });


// form used

<form id="contact-form" method="post" action="">
   <h2>Contact Us</h2>
   <div class="row two-col">
    <div class="first-col">
     <label>First Name</label>
     <input type="text" name="firstname" class="contact-firstname">
     <i class="first-i"></i>
    </div>
    <div class="second-col">
     <label>Last Name</label>
     <input type="text" name="lastname" class="contact-lastname">
     <i class="last-i"></i>
    </div>
   </div>
   
   <div class="row two-col">
    <div class="first-col">
     <label>Email</label>
     <input type="text" name="email" class="contact-email">
    </div>
    <div class="second-col">
     <label>Phone</label>
     <input type="text" name="phone" class="contact-phone">
    </div>
   </div>
   
   <div class="row one-col">
    <div class="single-col">
     <label>Message</label>
     <textarea name="message" class="contact-message"></textarea>
    </div>
   </div>
   
   <div class="row one-col">
    <div class="single-col">
     <input type="submit" name="contactformsubmit" class="contact-submit">
     
     <?php echo $msg; ?>
    </div>
   </div>
   
  </form>

 


about authors

Sandip Das

Web Developer

Once a legend said “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler.



POST COMMENTS

Leave a Reply

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