JQuery Postcode Validation

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
millsy007
Forum Commoner
Posts: 78
Joined: Wed Jul 02, 2008 7:00 pm

JQuery Postcode Validation

Post by millsy007 »

Hi
I am trying to ensure users can only enter a valid UK postcode
I can't get the code to work, any help greatly appreciated

Code: Select all

<html>

<head>
<script src="/jquery/jquery.js"></script>
<script src="/jquery/jquery.validate.js"></script>
<script>
$(document).ready(function(){

				$.validator.addMethod(
					"validpostcode",
					function(value, element, regexp) {
						var check = false;
						var re = new RegExp(regexp);
						return this.optional(element) || re.test(value);
					},
					"Please enter a valid postcode."
				);
   
    $("#commentForm").validate({
    
    rules: {
    	postcode: {
    		required: true,
    		minlength: 3,
    		validpostcode: "^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([        ])([0-9][a-zA-z][a-zA-z]){1}$"
    	},


    messages: {
    	postcode: {
    		required: "Please Enter Postcode",
		minlength: jQuery.format("You need to use at least {0} characters for your postcode.")
    	    	}
    }
    
    });
});

</script>
</head>

<body>

<form id="commentForm" method="get" action="">
 <fieldset>
   <p>
     <label for="cpostcode">Postcode</label>
     <em>*</em><input id="cpostcode" name="postcode" size="25" />
   </p>
   <p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>


</body>
</html>
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: JQuery Postcode Validation

Post by pickle »

Lots of information you still need to give:

What makes a valid UK post code? I'm guessing LDDD or LDLLDD or LDDLL (L = letter, D = Digit)
What exactly isn't working?
What are the inputs you're seeing?
What have you tried so far?
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
millsy007
Forum Commoner
Posts: 78
Joined: Wed Jul 02, 2008 7:00 pm

Re: JQuery Postcode Validation

Post by millsy007 »

I am confident the actual check should pick up the correct format, however I can't get it to carry out the check, I click submit and nothing happens. I was thinking I have a syntax error but I have tried everything I can with no joy?
Post Reply