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

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

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,

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

With a Javascript function

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

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

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Tom

    Hi, helpful post.

    im just wondering if i can call a javascript function like
    submitForm(){
    ..
    ajax call here
    }
    then the validation is separate..im just confused though

    Reply

Leave a Reply

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