?
Solved

How to Extend this jQuery code to validate empty input text fields

Posted on 2012-08-23
8
Medium Priority
?
525 Views
Last Modified: 2012-09-06
I am currently using the below code to check for a club code thats being entered into a input text field. I am checking it against a csv file, everything works great,

I would like to add some input validations for the 2 input fields, basically if they are left empty, just want to display a message saying fields are required and cannot be left empty.  I am already showing one more error when the club code is not correct,

I would like to extend that and show the above message.

So basically here are some of the error messages:

1) if the clubcode is left empty show message saying clubcode can't be empty
2) if the zipcode is left empty show message saying zipcode can't be empty
3) Clubcode can only be 8 characters and alphanumeric
4) zipcode can only accept zipcode ( basically zipcode 10 number format)
and finally the other existing error message.

I am not looking for the complete solution, just want to know how to extend my code  I have, even if someone can show me 1 and 3 I would highly appreciate it.

here is what I have so far which works.

                <h2>Testing Club Code</h2>
				 <p>Please Enter your Code below and click the Verify Code Button.</p><br /><br />
                 <div style="display:block;">
				 <form id="verify" action="TestCode.html" method="post" autocomplete="off">
				    <div class="form_row">
					 <span style="color:#A0000A;">* Required</span><br />
				  	 <label class="required"><em>*</em>Club Code:</label>
                     <input type="text" name="club1-code" id="club1-code" value="" /><br />
                     <label class="required"><em>*</em>Zip Code:</label>
                     <input type="text" name="zip-code" id="zip-code" value="" />
					  </div>
				   <div class="form_row">
				      <input type="submit" value="Verify Ski Code" name="verify-code" id="verify-code" class="button" />
                    </div>
                    </form>
                    </div>
                    <div id="ClubRegister">
		              <a class="Button" href="/TestResults.html"><span>Click to View Your Test Results</span></a>
					</div>
                    <div id="ClubError">
					  <div class="errormessage">Verification Failed. Please Enter a Valid club Code.</div>
					</div>
                    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">
var lines;

$(document).ready(function () {
    $("#ClubRegister").hide();
    $("#ClubError").hide();
	
	$.get("/clubcodes.csv", function(data) {
        $("#verify-code").data("testcodes", data.split(',')).click(function(e) {
            e.preventDefault();
            if ($.inArray($("input[name=club1-code]").val(), $(this).data("testcodes"))>=0) {
                $("#ClubRegister").show();
                $("#ClubError").hide();
				
            } else {
                $("#ClubError").show();
                $("#ClubRegister").hide();
            }
        });
    }, "text");

});

</script>     

Open in new window

0
Comment
Question by:niceoneishere
  • 4
  • 3
8 Comments
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38325031
$(function() {
   ....
// Assume we are good
   var rv = true;

   $('#verify').submit(function() {
      if ($('#club1-code').val() =='')) { 

         // Extend to include additional validation - regex etc

         alert('This field cannot be blank');

         // Set false return to prevent submit

         rv = false;
      }
      if ($('#zip-code').val() =='')) { 
         
        // Extend to include additional validation - regex etc

         alert('This field cannot be blank');
         rv = false;
      }
      return rv;
   });
});

Open in new window

0
 
LVL 44

Accepted Solution

by:
Rainer Jeschor earned 1000 total points
ID: 38325121
Hi,

I have modified JulianH script / extended (so please also points to him if it works):
$(document).ready(function () {
    $("#ClubRegister").hide();
    $("#ClubError").hide();
	
	$.get("/clubcodes.csv", function(data) {
        $("#verify-code").data("testcodes", data.split(',')).click(function(e) {
            e.preventDefault();
            if ($.inArray($("input[name=club1-code]").val(), $(this).data("testcodes"))>=0) {
                $("#ClubRegister").show();
                $("#ClubError").hide();
            } else {
                $("#ClubError").show();
                $("#ClubRegister").hide();
            }
        });
    }, "text");
	var rv = true;

    $('#verify').submit(function() {
		var characterReg = /^([a-zA-Z0-9]{0,8})$/;	
		var zipReg = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
		var clubInput = $('#club1-code').val();
		var zipInput =$('#zip-code').val();
		if (clubInput =='')) { 
			alert('This field cannot be blank');
			rv = false;
		} else {
			if(!characterReg.test(clubInput)) {
				alert('Maximum 8 characters');
				rv = false;
			}
		}
    
		if (zipInput=='')) { 
			alert('This field cannot be blank');
			rv = false;
		} else {
			if(!zipReg.test(zipInput)) {
				alert('Not a valid ZIP');
				rv = false;
			}
		}
		return rv;
   });
});

</script>     

Open in new window


HTH
Rainer
0
 
LVL 60

Assisted Solution

by:Julian Hansen
Julian Hansen earned 1000 total points
ID: 38325199
@RainerJ thanks I was going on the following comment from the author

I am not looking for the complete solution, just want to know how to extend my code  I have, even if someone can show me 1 and 3 I would highly appreciate it.

I have modified RainerJ's script below so points to him too :)
Modification is you don't need to check for blanks when you are doing a regex check - might as well just do the regex as it covers both
$(document).ready(function () {
    $("#ClubRegister").hide();
    $("#ClubError").hide();
	
	$.get("/clubcodes.csv", function(data) {
        $("#verify-code").data("testcodes", data.split(',')).click(function(e) {
            e.preventDefault();
            if ($.inArray($("input[name=club1-code]").val(), $(this).data("testcodes"))>=0) {
                $("#ClubRegister").show();
                $("#ClubError").hide();
            } else {
                $("#ClubError").show();
                $("#ClubRegister").hide();
            }
        });
    }, "text");
	var rv = true;

    $('#verify').submit(function() {
		var characterReg = /^([a-zA-Z0-9]{0,8})$/;	
		var zipReg = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
		var clubInput = $('#club1-code').val();
		var zipInput =$('#zip-code').val();
		if(!characterReg.test(clubInput)) {
			alert('Maximum 8 characters');
			rv = false;
		}
		if(!zipReg.test(zipInput)) {
			alert('Not a valid ZIP');
			rv = false;
		}
		return rv;
   });
});

</script>     

Open in new window

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 2

Author Comment

by:niceoneishere
ID: 38327900
Thanks for replying but its not working, #verify submit event gets never fired as #verify-code click event it taking the precedence .

Thanks
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38328235
It does for me - cut and pasted the code above into html - club codes not validating but the get('/clubcodes.csv') obviously won't work for me.

If I leave ZIP blank or enter letters I get the alert with the invalid input message.

Here is the code I am using
t66.html
0
 
LVL 2

Author Comment

by:niceoneishere
ID: 38329311
thank for replying the clubcodes.csv just contains some sample codes like TEST1234, TESTING1, CLUB1234

I tried again and it was not working for me sir
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38329442
When you say not working - can you be more specific? Was there an error.

Which browser are you using? Do you have access to Firefox with Firebug

Or Chrome with the Java Console activated?

Either of these will enable you to see any javascript errors that might be generated by your script and which might be causing the script to fail.
0
 
LVL 2

Author Closing Comment

by:niceoneishere
ID: 38372221
Thanks Guys
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Originally, this post was published on Monitis Blog, you can check it here . Websites are getting bigger and more complicated by the day. Video, images and custom fonts are all great for showcasing your product or service. But the price to pay in…
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question