Friday, 12 December 2008

grails: ajax powered validation [Update]

In a previous post, I outlined a method to perform textfield validation using jQuery. However a recent comment by Jan correctly pointed out a simpler method using grails' own ajax tag, <g:remoteField>.

So to implement this feature in a simpler way do the following,

Step 1: Import scriptaculous

<g:javascript library="scriptaculous"/>







Step 2: Code up the textfield and message div


<g:remoteField controller="member" action="validateUsername" paramName="username" name="username"

update="messageDiv" value="${fieldValue(bean:member,field:'username')}">

</g:remoteField>
<div id="messageDiv" style="color:blue"></div>






The message div will be populated with the ajax response, i.e. the uniqueness validation result.

Step 3: Code up the grails action


def validateUsername = {
        def message = ""

def inUse = ["homer", "marge", "bart", "maggie", "lisa"]

if (params.username)
{
if(inUse.contains(params.username))
{
message = "The username has already been taken. Please enter a different one"
}
else
{
message = "Username Ok !...."
}
}

render message

}




Not much change here other than the response messages.

And that's it.

3 comments:

Mark At HarvestInfotech said...

Dear Moon,
I have been trying to putup a sample application using AJAX and grails.
I have used Scriptaculo and application.
You can find the application at
http://github.com/markatharvest/sample-ajax-in-grails/tree/master

One of the goals of this application is to demostrate that we can use scriptaculo for grails AJAX and JQuery scripts for other things.
If you can take this application to next level.
Regards
Mark
http://markatharvest.blogspot.com/

Mo Sayed said...

@Mark,
Thank you very much for your invitation. Unfortunately I'm behind on a lot of pet projects that require my attention. So in this case I'm going to have to decline mate.

w3c said...

Nice information, I really appreciate the way you presented.Thanks for sharing..

http://www.w3cvalidation.net/