I am far from an accomplished web developer, but jQuery is one tool that helps out immensely in writing javascript that “just works”. As many of you are aware, browser differences create all sorts of havoc when trying to write code that navigates the DOM. And writing code from scratch to validate forms is a serious pain in the butt. So here are a few jQuery plugins that might make your life a little easier in that regard.
First off, there is the the combined magic of the jquery Form plugin from malsup.com which creates a nice AJAX-submitted form with one quick line of code
$('#form').ajaxForm();
Optionally, you can pass the .ajaxForm() function any options that you would normally pass to a regular jQuery .ajax() method like so….
Now that’s fun, but it can be extended just a LITTLE bit more with the jquery validate plugin. Here we can define some simple rules in JSON format and the validation plugin will automatically display customizable messages for any errors that are found before submitting the form. The validation function takes the option submitHandler to create the ajaxSubmit event from the Form plugin above.
Here is an example:
$('#contactus_form').validate({ submitHandler: function(form){ $(form).ajaxSubmit({ success: function(msg){ alert(msg); }, error: function(msg){ alert(msg); } }); }, rules:{ name:"required", email:{ required:true, email:true }, message:"required" }, messages: { name:"Name is required", email:{ required:"Email is required", email: "Email is in an invalid format" }, message:"Some message to the staff is required" }, errorLabelContainer:"#ajaxmsg", wrapper:"li" });
Obviously you need to validate the data in whatever script you are handling on the server side, but the jQuery error messages are a great way to improve your forms usability and they can be styled to be attractive and make any input errors very clear to your users.