|
Red Squirrel Reflections
Dave Hoover explores the psychology of software development
|
|
Sat, 17 Sep 2005Dabbling in Ajax Form Validation For the first time in a couple years I'm doing a bit of web development again. It's just an ultra-simple CRUD application. I had a few days to put it together and after spending the first day experimenting with several different J2EE frameworks (constrained to Java, no Rails for me [yet]), I decided to go with the JSTL database tag library. It fell into place very nicely. Once I had a Selenium test suite in place, I refactored the JSPs mercilessly to remove duplication. When I got around to implementing form validation, I opted for an Ajax approach using Prototype. In the form's onSubmit action, I used Prototype's Form.serialize and Ajax.Request to call a Servlet responsible for validation. The validation Servlet's sole resposibility (actually it delegated to a Validator) was to return error messages (Content-type: text/plain) based on the parameters it was given. If error messages were returned, they were displayed via Ajax.Request's onComplete. If no error messages were returned, the form posted to the URL in its action attribute. Naturally, my Selenium test suite didn't skip a beat because it can handle Javascript like a champ (since it runs in the browser). Here's the crux of it...
<head>
<script src="prototype.js"/>
<script>
function validate(form) {
new Ajax.Request('http://foo.bar/ajax/validate',
{ parameters: Form.serialize(form),
onComplete: function(request) {
if (request.responseText == "") {
form.submit()
} else {
// defined elsewhere
reportErrors(request.responseText)
}
}
}
)
return false
}
</script>
</head>
<body>
<form action="http://foo.bar/process" onSubmit="return validate(this)">
I found Ajax to be an excellent approach for form validation. There's no need to bother with maintaining state in order to reload the form. The validation code is easily test-driven with jMock (to mock out HttpServletRequest). And the whole process feels much faster since the page never reloads.
Note: I didn't have to worry about Javascript being disabled because this was for an internal audience using the latest browsers.
|