Ajax Validation With Play Framework

Supposed you have a form and you need to validate it with jquery along with Play framework. So, this is the way to deal with it. Play framework has a template tag (jsAction) which will render a javascript function during run-time. This function, basically, will parse the action and some parameters into a real url so template can send back the data to the controller. I do not find it so handy for ajax process, but since it is plugged into the framework, so we just go with it.

1. Create a User model with several properties:  ‘username’, ‘password’, ‘firstname’, ‘lastname’, ‘gender’, ‘lGender’, ’email’, ‘dob’,’country’, ‘agreeTerm’

2. Create a template with a form to save data

#{form @save(), id:'registerFrm' }

<ul class="error"></ul>

#{field 'username' }
<label>Username</label>
<input type="text" id="${field.name}" name="${field.name}" />
<br/>
#{/field}

#{field 'password' }
<label>Password</label>
<input type="text" id="${field.name}" name="${field.name}" />
<br/>
#{/field}

#{field 'firstname' }
<label>First name</label>
<input type="text" id="${field.name}" name="${field.name}" />
<br/>
#{/field}

#{field 'lastname' }
<label>Last name</label>
<input type="text" id="${field.name}" name="${field.name}" />
<br/>
#{/field}

#{field 'gender' }
<label>I am a </label>
<input type="radio" value="male" name="${field.name}" checked="checked"/> <label> Male </label>
<input type="radio" value="female" name="${field.name}" /> <label> Female </label>
<br/>
#{/field}

#{field 'lGender' }
<label>Looking for a</label>
<input type="radio" value="male" name="${field.name}" /> <label> Male </label>
<input type="radio" value="female" name="${field.name}" checked="checked"/> <label> Female </label>
<br/>
#{/field}

#{field 'email' }
<label>Email</label>
<input type="text" id="${field.name}" name="${field.name}" />
<br/>
#{/field}

#{field 'dob' }
<label>Date of Birth</label>
<input type="text" id="${field.name}" name="${field.name}" />
<br/>
#{/field}

#{field 'country' }
<label>Country</label>
<input type="text" id="${field.name}" name="${field.name}" />
<br/>
#{/field}

#{field 'agreeTerm' }
<label>Agree with <a href="#">Term of use </a> ? </label>
<input type="checkbox" id="${field.name}" name="${field.name}" />
<br/>
#{/field}

<label> </label>
<input type="submit" id="submit" value="Continue">
<br/>

#{/form}

3. Dont forget to add “set ‘moreScripts’” tag at the beginning of the template


#{set 'moreScripts'}

....Magic jquery code goes here....

#{/set}

4. Put these code inside the set tag above

<script type="text/javascript">

    var listAction = #{jsAction @User.save(
                        ':username',
                        ':password',
                        ':firstname',
                        ':lastname',
                        ':gender',
                        ':lGender',
                        ':email',
                        ':dob',
                        ':country',
                        ':agreeTerm'
                    ) /};

    $(document).ready(function() {

        $('#submit').click (function(event) {

            event.preventDefault();
            $.post (listAction({
                username: $('#username').val(),
                password: $('#password').val(),
                firstname: $('#firstname').val(),
                lastname: $('#lastname').val(),
                gender: $('#gender').val(),
                lGender: $('#lGender').val(),
                email: $('#email').val(),
                dob: $('#dob').val(),
                country: $('#country').val(),
                agreeTerm: $('#agreeTerm').val(),
                }), function(data){
                    $('.error').html(data);
            });

        });

    });

</script>

Ok, too many magic lines,rite? What the hell is listAction variable doing here ? Here is the thing: you open your browser, go to the url which will render the template and in your firefox, press Ctrl + U to view the html code of the page. This is what Play framework render the line listAction:

var listAction = function(options) {var pattern = '/user/save?username=:username&email=:email&dob=:dob&lGender=:lGender&gender=:gender&lastname=:lastname&firstname=:firstname&agreeTerm=:agreeTerm&password=:password&country=:country'; for(key in options) { pattern = pattern.replace(':'+key, options[key]); } return pattern } 

Do worry too much about the whole rendered function. You just need to know that in the end, it will return a pattern which contains the whole url with all the value inside the form. So, that means listAction will contain a url string, nothing else. Now you have a string url, what you need to do is putting it to the post function of Jquery and then waiting for the result from the controller.

5. Controller code:

Since I pointed the form action to the save function of User controller, now this is the save function

public static void save(
        @Required(message="Username is required") String username, 
	@Required(message="Password is required")String password, 
	@Required(message="Firstname is required") String firstname,
	@Required(message="Lastname is required") String lastname,
	String gender, String lGender,
	@Required(message="Email is required") String email,
	@Required(message="Birthdate is required")String dob,
	@Required(message="Country is required")String country,
	@Required(message="You have to agree with the terms")boolean agreeTerm) {
        
        if (models.User.find("byUsername", 
              username).first() != null) {
            renderText("Duplicate name");
        } else {
            models.User user = new models.User(username, 
                    password, firstname, 
                    lastname, gender, 
                    lGender, email, 
                    country, dob, 
                    agreeTerm);
            validation.valid(user);

            if (validation.hasErrors()) {
                renderText("Wrong values");
            }
        }
        .......       
}

So, that is all the things about ajax validation along with Play framework

Leave a comment