Log In | Register | March 28, 2024

Share
 

jQuery Programming - September 28, 2010

jQuery Basic Form Validation

With this tutorial, you will learn how to add basic validation to any form. This lesson will be a continuation of my other tutorial for creating an ajax php contact form. Click here if you have not yet gone over that one.

Lets start by opening our code with our jQuery and form. We want to create a way that we can choose which fields to validate without much work. For this tutorial I will be adding an attribute to each of the fields that I want required, in this case being the name and email fields.

<form action="process.php" method="post" id="contact_form">
<div>
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" rel="req" value="" tabindex="1" />
</div>
<div>
<label for="email">Your Email:</label>
<input type="text" name="email" id="email" rel="req" value="" tabindex="2" />
</div>
<div>
<label for="message">Message:</label>
<textarea cols="40" rows="8" name="message" id="message"></textarea>
</div>
<div id="loader">
<input type="submit" value="Submit" />
</div>
</form>

You will see that I added the rel attribute with the value of req to each of the two fields.  This is just for me to use as an identifier when I create the validation portion for the script. Now that we have our HTML markup in place we need to create the JavaScript to handle it.

The first thing we need to do is create some variables.

var submit_form = false;
var req_fields = $('input[rel=req]');
var field, pcount = 0;

In the above code, I created the variables submit_form, req_fields, field, and pcount. The submit_form variable will be used as a Boolean to decide whether or not we should submit our form. The req_fields variable will store all of our inputs that have the attribute rel=req. The variable field is initiated so that it can be used later on in our loop. In the loop it will store the value of the current field being checked. Finally the pcount variable, which will store an integer count of fields that were not filled in by the user.

After declaring our variables we want to use the .each method that is apart of the jQuery library which will loop through a given array. We will append the .each method to our req_fields variable which is storing all of our required fields in an array.

req_fields.each(function(){
field = $(this).val();
if(field == '' || field == 'Required') {
$(this).css('border', '1px solid red').val('Required');
pcount += 1;
} else {
$(this).css('border', '1px solid green');
}
});

What we are doing in the above code is looping though each of our required fields. Then within the .each method we are setting the variable field to the value of the current required field. Checking if the value of the field is empty or set to Required. If so we then set the border of the current field to red and apply the value Required to it. Within that if set, we are also adding +1 to our variable pcount that way we can let our script know later that we have fields that are not filled which are required. Our else part of the if places a green border around the fields that are not empty that way you can let the user know that those fields are ok.

After this portion we need to create an if statement that will check out pcount variable. This if statement should go outside of our.each loop.

if(pcount == 0) {
submit_form = true;
}

What this if statement is doing is checking if our pcount variable is equal to 0. If so set the submit_form variable to true.

Then finally we wrap our ajax portion of our script within a if statement. The if will check if our submit_form variable is set to true, and if so process the form.

if(submit_form) {
$('#loader', form).html('<img src="loader.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
}

That’s it, now you should have a basic validation, which you can easily apply to any of your forms.

Ajax Contact Form with Basic Validation

Post By: | FavoriteLoadingAdd to favorites

7 Comments

kyleinsea
Wednesday, September 29, 2010

Works Great! I added the following block of code to validate e-mail addresses:

var emailFormat_fields = $(‘input[rel=emailFormat]‘);
var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
var field2, pcount2 = 0;
emailFormat_fields.each(function(){
field2 = $(this).val();
if(!filter.test(field2) || field2 == ‘Invalid E-Mail Address’) {
$(this).css(‘border’, ’1px solid red’).val(‘Invalid E-Mail Address’);
pcount += 1;
} else {
$(this).css(‘border’, ’1px solid green’);
}
});

if(pcount == 0 && pcount2 == 0) {
submit_form = true;
}

Just change the rel value of the e-mail address input to:

rel=”emailFormat”

I’m not sure if this is the best way to handle this situation, but it works.

kyleinsea
Thursday, September 30, 2010

noticed an error with my code above…

it should be pcount2 += 1;

OMG카지노
Friday, November 20, 2020

ON THE INTERNET CASINOS ARE A EXCELLENT NIGHT TIME IN https://www.omgqq.com

OMG카지노
Friday, November 20, 2020

If you’re looking for a proven and reliable casino company, this is it. You can enjoy various games such as baccarat, blackjack, roulette, and big wheel safely. https://www.bbdd66.com

OMG카지노
Friday, November 20, 2020

https://www.bbdd66.com/yes 예스카지노

인터넷바카라
Wednesday, March 10, 2021

바카라사이트 some body feels like very interesting

바카라카지노
Thursday, April 1, 2021

온라인 및 실제 상대와 카지노 게임을하고 싶으십니까? 이 라이브 카지노 사이트를 확인하세요 정선카지노

Leave a Comment



Need Help? Ask a Question

Ask anything you want from how to questions to debug. We're here to help.

You Must Be Logged In To Post A Question.

Log In or Register