Archive

Posts Tagged ‘jquery’

Tips for jQuery validation plugin

August 13th, 2009 ITmeze 4 comments


Because I currently work with a couple of projects where I extensively use jQuery framework, together with it’s plugins I decided to write a post in which I can gather all of my ideas, tips that i have arrived during my work with this library.  I am a kind of guy that has a huge mess not only on his computer’s desktop but even within project files. It happens that when I arrive a problem, and I am sure I have figured it out in some other project but it usually takes me ages to dig through all of them to find even simplest solution. That is why I decided that I really need a place for all my tips and tricks, so I can find them easily.

This post focuses on jQuery Validation plugin, as i think this is the second thing i add to my project – after jQuery core file :) . I will add more and more tips from time to time as soon as I find something worth to write down.

Ever worked with one of most popular jQuery validation plugins? This is extremely powerful and yet flexible plug-in that  makes form validation in javascript really easy.

Beside that fact that it already contains most popular validation rules, like checking field length, validating email or url format, it enables you to write your own “rule”.

1. Adding new method

Plugin supports method called ‘equalTo’. It is widely used – especially we request password confirmation. What is not supported is ‘notEqualTo’ method. Not that popular but can be useful from time to time. Let us say we have a field that needs to be different from other field, like new password has to be different than old password – maybe not the best choice but draws the picture.. OK, I guess recommended way to do that would be to add new method to jQuery validation plugin:

  jQuery.validator.addMethod("notEqualTo",
                             function(value, element, param) {
                                  return this.optional(element) || value != $(param).val();
                             }, "This has to be different...");
  $("#change-password-form").validate({
                rules: { ... newPassword: { notEqualTo:'#currentPassword' } },
                messages: { newPassword: { notEqualTo: "New password has to be different than old one" } }
  });

2. Preventing double form submission

Another common issue every web developer arrives sooner or later is so called ‘double form submit’. Or going further on ‘multiple form submit’. It happens when user accidentally presses submit button couple of times, causing form to be send multiple times. If we have validation plugin for our form we can make use of submitHandler method to disable button after form is submitted.

  $("#sample-form").validate({
                submitHandler: function(form){
                    if(!this.wasSent){
                        this.wasSent = true;
                        $(':submit', form).val('Please wait...')
                                          .attr('disabled', 'disabled')
                                          .addClass('disabled');
                        form.submit();
                    } else {
                        return false;
                    }
                }
            });

3. Turning on/off validation under certain conditions

It happens quite often that we require input in certain field only when some other element is selected. I just finished making web page that allows users to subscribe to newsletters on their request.  If user selects certain check-box – it means he want to subscribe and we require from him to put valid email in other field.
Otherwise, we want to keep validation turned off. To do this, we use :

<label for="cbxSubscribe"> Would you like to subscribe?</label>
<input id="cbxSubscribe" type="checkbox" />
<input id="txtSubscriptionEmail" name="subemail" />
$("#sample-form").validate({
  rules: {
    txtSubscriptionEmail: {
      required: "#cbxSubscribe:checked"
    }
  }
});

As simple as that. Element ‘txtSubscriptionEmail’ is required depending on evaluation of ‘#cbxSubscribe:checked’ expression.

4. Use CDN from Microsoft AJAX

Surprise, Surprise! ASP.NET MVC 2 (since preview 2 i guess ) includes jQuery validation plugin to provide client side validation. Definitely good news!

Moreover, Microsoft now provides CDN for plugin:

As well as documentation for visual studio – this would allow IntelliSense to work under visual studio (2008 and up):

You should make use of CDN wherever possible. It saves you bandwidth, most probably Microsoft serves content faster and there is always a chance your visitors will have it cached already. Note that Google offers CDN for jQuery and some other libraries: Google AJAX libraries API.

Stay tuned for more updates….

I will keep on adding more tips in future.

Categories: web development Tags: , ,

Firefox 3.0: 411 Length required with JQuery

July 21st, 2009 ITmeze 5 comments

I am currently working on a small project for my own. My favourite (and the only one tester) was complaining on some of “ajax” features. Tests were done with use of Firefox 3.0 – I was developing on Firefox 3.5 and had absolutely no problems with those problematic features. Anyway I decided to check this out an downloaded 3.0 version ( most recent is 3.0.11). You can have multiple instances of Firefox on Your machine – just make sure You install them in separate directories. Then the best would be to create different user profiles – like one default and one for testing. You can manage profiles using :

firefox.exe -ProfileManager

And then You can run prev version by:

\path\Firefox 3.0\firefox.exe -P test_profile -no-remote

Having this set up You can test in Firefox 3.0. I was able to reproduce error and check what is going on in firebug.
I was receiving HTTP 411 error, which says:

Your Web server thinks that the HTTP data stream sent by the client (e.g. your Web browser or our CheckUpDown robot) should include a ‘Content-Length’ specification. This is typically used only for HTTP methods that result in the placement of data on the Web server, not the retrieval of data from it.

It looks like jQuery (1.3.2) ajax calls with data parameter set to ‘null’ was causing this to happen.

Simple solution for me was to set ‘{}’ as data parameter value instead of ‘null’. Moreover, You can change method that I already mentioned about, postJSON with this fix:

$.postJSON = function(url, data, callback) {
     if(data == null)
         data = {};
     $.post(url, data, callback, "json");
};

BTW I already use Firefox 3.5 during development – it consumes less resources than previous versions () so I strongly recommend upgrading to newest version.

Categories: web development Tags: , ,