Shaun Mccran

My digital playground

01
M
A
Y
2011

Adding custom validation rules to the JQuery Validation Plugin

The http://bassistance.de/jquery-plugins/jquery-plugin-validation/ JQuery Validation plugin is a fantastic option for adding client side JavaScript validation to your forms.

It comes with quite a few pre defined validation methods (you can see them here: http://docs.jquery.com/Plugins/Validation#List_of_built-in_Validation_methods), but what if one of your fields requires a bespoke validation type, for example matching the first N characters of a string.

Well its pretty easy to do, you just have to plan your new rule, and programatically add it to the plugin. In the example below I am going to match the string '123456' and check it as a rule, alongside the existing rules.

I'm assuming you have already imported the JQuery library and Validation plugin. Next we use the addMethod() function of the Validation plugin to add a new custom method. This accepts a few different arguments, as detailed below:

Name (String)
The name of the method, used to identify and referencing it, must be a valid javascript identifier

Method (Callback)
The actual method implementation, returning true if an element is valid. First argument: Current value. Second argument: Validated element. Third argument: Parameters.

Message (string / function)
The default message to display for this method. Can be a function created by jQuery.validator.format(value). When undefined, an already existing message is used (handy for localization), otherwise the field-specific messages have to be defined.

As an example I have created a new rule called 'pattern-match', this rule will check if the passed in element is required 'this.optional(element)' OR if the first six characters match the designated pattern, in this case '123456'.

view plain print about
1<s/cript language="javascript">
2$(document).ready(function(){
3
4$.validator.addMethod("pattern-match", function(value, element) {
5
6return this.optional(element) || (value.substr(0,6) == '123456');
7
8}, "* match the string");
9
10});
11</script>

This code creates the new validation method, now we can reference it in our validate() method just like all the pre existing methods.

view plain print about
1<s/cript language="javascript">
2$(document).ready(function(){
3
4$("#form").validate({
5
6errorContainer: "#error",
7errorLabelContainer: "#error ul",
8wrapper: "li",
9
10rules: {
11numberField: {
12
13required: true,
14pattern-match: true,
15minlength: 8,
16maxlength: 10 }
17    },
18
19messages: {
20
21numberField: {
22
23required: "Please enter a number",
24pattern-match: "Number does not match 123456",
25minlength: "Number must be at least 8 characters long",
26maxlength: "Number cannot be more than 10 characters long"
27}
28
29    }
30});
31
32});
33</script>

Just add it in with the other methods, and specify the the error message that goes with it.

The addMethod() function will take any form of custom validation that you can write in standard JavaScript, so it should be possible to accommodate any bizarre rules you might want to come up with.

21
A
P
R
2011

Using URL re-writing to provide friendly 404 error screens

A while ago I wrote a blog entry about changing the 404, page not found, handler in IIS ( http://www.mccran.co.uk/index.cfm/2010/3/2/Changing-the-404-template-handler-in-IIS). More recently I've moved some hosting to a Linux based server, and I didn't have the same server side options available to me.

The problem I've had setting up a global 404 handler is that I can setup a front end friendly error page easily enough, but the method used to set it up hugely affects my ability to actually report what the error was.

For example in the Linux admin area I can specify a path to a 404 template, but this appears to actually relocate the user to the file specified, leaving any error and its associated information behind.

Similarly the 'onMissingTemplate' Application.cfc function only fires when a missing ColdFusion template is requested. Not just any old url that someone tries on my site.

What I eventually ended out with is a URL rewrite rule that catches any page request that does not match an already defined re-write rule.

So if a user asks for 'www.mysite.com/contact/' the following rule would be found and used:

view plain print about
1RewriteRule ^/contact/$ index.cfm?go=contact

But if they asked for any non matched rule, for example 'www.mysite.com/contactx/', or 'www.mysite.com/hack-attempt/' then the following rules would kick in and divert the user:

view plain print about
1# Error handlers
2RewriteRule ^([^/.]+)/$ index.cfm?go=error&error=$1
3RewriteRule ^([^/.]+)$ index.cfm?go=error&error=$1

The rule above just sends a user to my error page. It also appends the string matched in the Regular Expression to the end of the URL (error=$1).

This is so I can pick it up in a ColdFusion variable scope and log it, to actually let me know what the error was.

There is another documented way of using URL re-writing to redirect users to custom error pages. You can use custom error pages for any error type as long as you know its number by adding the following to your re-write file:

view plain print about
1ErrorDocument errorNumber path/file.htm

As an example if I had the file 'error.htm' in the root directory of my site and I wanted to use it for a 404 error I would use:

view plain print about
1ErrorDocument 404 /error.htm

Some of the more common server error responses are:

view plain print about
1401 - Authorization Required
2400 - Bad request
3403 - Forbidden
4404 - Wrong page
5500 - Internal Server Error

17
A
P
R
2011

Book preview: JQuery 1.4 Animation Techniques: Beginners Guide

I've just been sent a preview copy of the new JQuery 1.4 Animation techniques: beginners Guide from Packt publishing.

It is pitched as:

view plain print about
1Quickly master all of jQuery's animation methods and build a toolkit of ready-to-use animations using jQuery 1.4

I'll be reading through it over the Easter break and putting a review up here, so keep an eye out.

In the meantime you can see a synopsis and read a preview chapter here:

https://www.packtpub.com/jquery-14-animation-techniques-beginners-guide/book

13
A
P
R
2011

Triggering functions when closing a fancybox pop up

The FancyBox JQuery plugin is a popular lightbox style plugin that allows you a variety of options to 'pop' different types of content up into a users view.

I needed to have the parent page change when the user had performed an action within the pop up. But how to do this?

FancyBox (http://fancybox.net/) has a 'onClosed' option to allow you to embed a function call whenever the user closes the lightbox.

The format of this is a little tricky, so here is an example:

view plain print about
1// pop up handler
2$.fancybox({
3    'autoDimensions':    false,
4    'speedIn'            : 600,
5    'speedOut'            : 200,
6    'overlayShow'        : true,
7    'width'            : 440,
8    'height'            : 340,
9    'type'            : 'iframe',
10    'scrolling'            : 'no',
11    'transitionIn'        : 'elastic',
12    'transitionOut'        : 'fade',
13    'enableEscapeButton'    : 'true',
14    'overlayOpacity'        : 0.5,
15    'title'            : '',
16    'href'             : 'yourpage.htm',
17    'onClosed'            : function() { alert('closed'); }

You can build any function you want in this call, it is normal JavaScript after all, if you just wanted to reload the page you could have a refresh function:

view plain print about
1function() {
2
3parent.location.reload(true);
4
5}

This seems to work for any method of closing the Fancybox as well, so it will always fire.

_UNKNOWNTRANSLATION_ /