Need to use jQuery to validate form inputs

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
drayarms
Forum Contributor
Posts: 134
Joined: Fri Dec 31, 2010 5:11 pm

Need to use jQuery to validate form inputs

Post by drayarms »

As the topic states, I'm trying to validate form inputs using jQuery. The input field in question is a text field, with id "input_zip". It is supposed to validate US zip codes. The success or error message needs to be printed in a div with id "zip_error". register_error and "register_success" are css classes which represent the style for the message that would be printed in "zip_error" div if the input doesn't and does match respectively. So here is the code. Needless saying that it doesn't work and since this is my first attempt to write such code, I'm at a total loss. I'm not sure if it is the matching pattern that is wrong or if the entire algorithm is wrong. I used alerts instead of printing out text in "zip_error" div, to no avail.

Code: Select all


		<script type='text/javascript'> //Validate registration inputs


			$(document).ready(function() {
 

				$("#input_zip").keydown(function(){

					var zip_value = $(this).val();

					var zip_pattern = "^([0-9]{5})$";

					if(!zip_patten.match(zip_value)) { //If the current value doesn't match accepted pattern 

        					$("#zip_error").html("<span class = 'register_error'>Enter a valid zip code</span>");

   					} else {$("#zip_error").html("<span class = 'register_success'>Valid zip</span>"); }


				});   				

			});

			



		</script>



User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Need to use jQuery to validate form inputs

Post by califdon »

I don't think you want to use the keydown event. That means that you try to match an entire zipcode every time the user hits a key. I'm sure there's an event for when the cursor is removed from the input element (blur?), but I don't have time now to look it up. Maybe you could do that.
Gopesh
Forum Contributor
Posts: 143
Joined: Fri Dec 24, 2010 12:48 am
Location: India

Re: Need to use jQuery to validate form inputs

Post by Gopesh »

Hi,Check this Fiddle http://jsfiddle.net/UGaJh/7/.
As califdon said dont use keydown event,use blur() or change() event.
Hope it helps.
codeinsects
Forum Newbie
Posts: 1
Joined: Fri Mar 09, 2012 6:27 am

Re: Need to use jQuery to validate form inputs

Post by codeinsects »

Keydown won't work in your case. It will always check once a key is pressed, which is not what you want. Instead of keydown event you should use the blur event.
Post Reply