How to validate the form using jQuery, prevent submission of form and show proper error messages in a specified div?

1.5k Views Asked by At

I'm using jQuery v1.7.1 in my project.

I've following HTML form:

<div class="alert-danger">                  
</div>
<form action="index.php" class="navbar-form pull-right" id="formzip" method="post">
  <input type="hidden" class="form-control" name="op" id="op" value="zip_code">
  <input type="hidden" class="form-control" name="form_submitted" id="form_submitted" value="yes">
  <input style="width: 115px;" type="text" placeholder="Enter the zip code" name="zip" id="zip" value=""> <i class="icon-zip" style="margin-top:3px;" onclick='$("#formzip").submit();'></i>
</form>

Now here I want to validate the form with id="formzip" using jQuery. Following validations need to apply:

  1. If the input field having id zip doesn't contain any value at the submission of a form.
  2. If the input field having id zip contains invalid US zip code value or any value which is not a valid US zip code.

I want to show relevant error messages in a <div class="alert-danger"></div> and want to prevent the form from submission. That is the page currently displaying should remain as it is.

The necessary regular expression string to validate US zip code is as follows :

"/^([0-9]{5})(-[0-9]{4})?$/i"

Can someone please help me in achieving this functionality?

It will be of immense help to me if someone could help me.

thanks for spending some of your valuable time in understanding my issue. If you want any further information regarding my issue please feel free to ask me.

Waiting for your precious replies.

Thanks in advance.

3

There are 3 best solutions below

2
Umesh Sehta On BEST ANSWER

you can do something like this:-

$(function(){
$('#formzip').on('submit',function(){
   if($('#zip').val()=='')
   {
       $('.alert-danger').html('zipcode is empty');
       return false;
  }else if(!isValidZip($('#zip').val()))
  {
      $('.alert-danger').html('zipcode is invalid');
      return false;
  }
});
});

function isValidZip(zip) {
   var pattern = new RegExp(/^([0-9]{5})(-[0-9]{4})?$/i);
  return pattern.test(zip);
 };

or if you want to show same message you can do this:-

$('#formzip').on('submit',function(){
  if(!isValidZip($('#zip').val()))
  {
      $('.alert-danger').html('zipcode is invalid');
      return false;
  }
});

Demo

0
VishalDream On

I hope bellow content and reference can help you

http://jqueryvalidation.org/

and view Demo from

http://jqueryvalidation.org/files/demo/

0
Rajitha Bandara On

You do not need to use any custom validation library for this. First stop the submit event and let your validation rules run. Remove your onClick event for i elem.

Just some thoughts. Another person might have different approach.

$(document).ready(function(){
$(".icon-zip").click(function(){
$(".alert-danger").html("");
var zip = $("#zip").val();
//run validations
var regex = /^([0-9]{5})(-[0-9]{4})?$/i;
if(!regex.test(zip)){
  $(".alert-danger").html("Invalid zip");
  return;
}

//if all ok
//do ajax request to server with your data
//Handle server response in ajax callback functios
$.ajax(function(){
 url:"index.php",
 type:"post",
 dataType: 'json',
 data: $("formzip").serialize(),
 success:function(data){
   if(data.status == "ok"){
     // show success msg
   }
 },
error:function(data){
     // show error msg
}

});

});
});