Simple Client Side Ajax Validation

14 / Mar / 2011 by Manoj Mohan 2 comments
Well my second month into work and I have started discovering things that are very trivial, but can save you a whole lot of time .. if you could get to know them better .
One of those things was with jQuery.
Now working with a normal submit form, a jQuery Validate Plugin works superbly. You simply give
class = required
and it does the job.

But when do the same with an Ajax call .. the Ajax call goes out without a validation.. which is what you don’t want. The call should only go out if the validation passes . Now faced with this I started to write a custom method … but on some reading up, found out that there actually exists a way to do this through the Plugin itself.

The .form() method coupled with a .validate gives you a Boolean value i.e true if validated or false if not.

Something like

function validateForm() {
if ($(‘#form’).validate().form()) {
// (Put your Ajax Call here)

In this way the Ajax call went out only if the .validate().form() returned true.
Another usecase where I used it was when the whole form was when the whole form went through an Ajax call.
I used a <g:formRemote> tag . Now it doesn’t have a ‘onSubmit‘ of the normal form but it does have a ‘before‘ attribute that works somewhat similarly.
So now,

<g:formRemote name="searchPage" id="searchPage" url="${[controller:’eventInstance’,action:’executeSearch’]}" update="searchUpdate" before="return validateSearchForm()">

With a Javascript function

function validateSearchForm() {
if ($(‘#searchPage’).validate().form() && checkDate()) {
return true;
else {
return false;

So in this way the page would be Ajaxified if both of those methods returned true …

Hope this helps ..

Manoj Mohan
Manoj (at) Intelligrape (dot) com


comments (2)

  1. Tom

    Hi, helpful post.

    im just wondering if i can call a javascript function like
    ajax call here
    then the validation is just confused though


Leave a Reply

Your email address will not be published. Required fields are marked *