We’re going to take what was put together in the last 3 videos and now include some server-side validation that will appear asynchronously. This is an example of using Zend_Form as a validation tool via JSON.
Grab a copy of the project or browse the repository.
UPDATE: as a couple people have mentioned, you can cut down your IndexController even more by using the Zend_Json view helper:
public function validateformAction()
{
$f = new Form_Registration();
$f->isValid($this->_getAllParams());
$this->_helper->json($f->getMessages());
}
Enjoy!

Beautiful
Thank you for the vid.
Wow…. Great. Exactly what I was tracking…
Thanks Jon!
Thank you for this great tutorial. Finally something that is easy to understand.
Thanks a lot !!
Thanks.
John, Many developers don’t use plain html forms any more, instead use an Ajax framework like ExtJS that generates fields with javascript.
In that case, do you recommend using just Zend_Filter_Input ?
Thanks.
+1 for a jQuery screencast although I would really like to see a Zend specific Dojo screencast.
Cool, I didn’t know that this is so “simple”.
You helped my relly much, thank you!
Thanks for awesome tutorial. It’s really useful. May I just ask what setup do you use for development (xAMP, CPU, RAM, etc)? The response seems really fast, but I can’t get below like 500ms without caching on my C2D6400/4G/xampp
Awesome, as aways. Thank you Jon!
One simple optimization suggested:
- $this->_helper->viewRenderer->setNoRender();
- header(‘Content-type: application/json’);
- echo Zend_Json::encode($json);
// disable view renderer, modifies header and Json it!
+ $this->_helper->json($json);
By the way, I too would like to hear something about Zend_Dojo_Form.
Cheers!
Thanks for video!
Just one question why didn’t you use for example:
$this->_helper->json->sendJson($data);
to send JSON and disable layout?
I’m running MAMP on a macbook pro, C2D 2.8Ghz with 4GB of RAM…
Hey Aju & Marcelo,
thanks for mentioning this. You’re both quite right that this would cut down the number of lines of code! It’s a bad habit from when the view helper didn’t exist.
Now the problem is that there is really many of helpers so you can easily get lost
Good idea to use jQuery for client side validation! It’s imho a slightly better approach than Jani Hartikainen posted (http://codeutopia.net/blog/2008/04/04/client-side-validation-with-zend_form).
But I have several concerns about the php implementation:
1) Why don’t you use the ZendX_JQuery component? It has a view helper which enables jQuery with a specified version from Google’s CDN completely automatically. You’re able to do such:
jQuery()->enable()->addOnload(‘javascript here’)?>
or
jQuery->setVersion(’1.4′)->enable() ?>
etc
When you use addOnload() the script is encapsulated inside a $(document).ready(function(){
});
It performs much better than waiting your javascript to complete.
2) JSON responses should only respond to XHR so people with no js can still use your application. Therefore I should suggest using the context switch action helper which will be initialized when you send a XmlHttpRequest with a format parameter requesting a JSON response.
Now you have a special action inside the controller responding only for this validation. I’d suggest you send the POST data to the indexAction. Inside the action you can always distinguish the JSON validation request and use a seperate method to handle the request. Eg a _valdiateJSON($data){} which is called by the indexAction().
In your doValidation function you could take advantage of jQuery’s serialize function to automatically serialize your form elements:
http://api.jquery.com/serialize/
Hi. Great tutorials!
Just one suggestion when working with ajax, why not taking advantage of the ContexSwitch action helper?
Great tutorial!
Thanks!
Good stuff! Easy to understand.
Jon,
Thanks for the video. In jQuery you can serialize a form like
var formdata = $(“#formid”).serialize();
Hi Jeremy,
good point!
Hi Jurian,
r.e. #1: something in ZendX is not inside the Zend libraries and so I’m reluctant to produce videos about it quite yet, although I know there’s a huge demand out there for jQuery / Zend interaction and the ZendX_JQuery component is great.
#2 people can still use this app if they don’t have js (the javascript code would just be ignored). Sending the post data to indexAction is a moot point that speaks more to where we put our JSON interface in our application. By making a Zend_Form object, we are explicitly decoupling the form object from the action in question. By moving the validation code back into indexAction, we’re re-introducing this coupling. I would rather treat the object separate from the controller, because it is separate from the controller. If you’re writing a 1-to-1 relationship between forms and controller actions, then I would agree with combining the two.
I dont know why the publisher of this video uses echos in the controller. Apart from using the json helper u can use the responseObject to set headers and the response body. Its a much more clean then echoing in the controller level. Another option is using the context switch for the validateAction.
Modifying headers by
header(“Content-type: application/json”);
doesn’t work for me, but Zend has this fancy method in request object:
$this->_response->setHeader(‘Content-Type’, ‘application/json’);
(from Action controller) which works perfectly well. Also you can get request object from front controller:
Zend_Controller_Front::getInstance()->getRequest();
(from top of my head).
We are using mootools at work, but your screencast has some nice ideas, thanks for that! All your screencasts rock!
Cool screencast. But just letting you know, you could use the jquery serialize function to easy serialize your form (http://api.jquery.com/serialize).
I havent watched the full video yet, just got to the point where you’re asking about the interest in more jquery vids and figure i had to pause and post.
+1 for more jquery vids.
?
Works really good, except on File Uploads.
The validator always returns fileUploadErrorIniSize error.
Maybe anyone experienced the same or has a solution
isValidPartial() solves the problem as described above
Nice screencast keep up the good work!!
Any way to set the key in the json response? IE isEmpty,recordFound etc….it would make iterating the json a lot easier. Thoughts?
Any idea on how to do this with mootools? and the whole form not just as you leave a field. that would be great.
First, thanks for your greats videos.
In jquery code of index.phtml you could use
var data = jQuery(this).serialize();
Sorry, no way. My mistake.
What a wonderful cast!!
I’ll implement this type of javascript validation soon in my projects
I like this video,very good.
Hi Guys,
I loved the tutorial, very very usefull…especially for someone like me that is just starting to learn the zend framework.
I have a question, and i will be grate if someone could help me to figure out a good answer (anyway I’m talking with experts, than i not have doubt that the answer will arrive:)).
I built a form (using zend form, and all the suggestions that i found very usefull in all the tutorial that i saw until now).
Now this form have also ajaxification..that works pretty well.
Now what I want to do is be able to manage my ajax function (jquery) using the message of errors that come from the zend structure.
In other words, I’d like to create a function (php) that will take as parameter two variable: $status (that can be 0 if the zend form validate bring errors, and 1 when everything is ok and we can just continue the registration process), and $txt( that will carry exactly the error message that come from zend,in other words what i can take with the getmessage(), or if there are not error will just bring a jump to the next page(the registration is done)).
In this way, if i pass to the jquery function that handle the ajax call, the parameter txt or status, i can controll the way in which the div that i create to show the errors, can be hidden or not.
How i can realize such type of function in zend? I done already in php, but not using zend framework, what i can’t figure out is how i can create a msg function that show the errors as i said before (msg($status,$txt))?
There is a way to access to the errors array in zend, and build a custom error class that will create this msg function?
What i’m trying to do, is to be able to do something like in the facebook registration form.
Some suggetsions??
thanks so much
TT
Hello,
I have a problem.
I followed the tutorial, but I do not work.
I am not getting any error message.
What can I check?
Thanks
Thanks for this excellent post!
the video is not working ,it stops after 12 minutes
would you please reload it
Thanks…that’s really amazing.
Very easy to use
5. Good day, As I was looking over the internet, I found this, your weblog website. In fact most of the individuals comments are relevant and, you’re brilliant in making write ups.
Hi
I have some problem with form element “autocoplete” and validate this form when i put youre script.
u have some idea why?
greate tutorial..
cheers m8
Hi Poul,
please give us some more information about your problem, maybe log or stack trace will be helpfull
Best reagards!
Doing this works for most of the form elements, but it broke Captcha and CSRF.
I got my code working with those element types by using isValidPartial instead of isValid in my validate Action and by overriding isValidPartial in my form to unset any data related to captcha and csrf
public function isValidPartial(array $data)
{
unset($data['captcha']);
unset($data['csrf']);
parent::isValidPartial($data);
}
wow, this is amazing, I hope soon can put it all together on my web.
Thank you !
Nice Article, Thanks
Hi,
first of all – great cast (as always:). I have found out, that this way of ajax validation works wrong, when the input element is filled by jquery`s datepicker and is set to required.
It seems the problem is that the “blur” event is fired when the datepicker window appears (because at that time thi input looses focus) – so ajax grabs its value value to early (it is empty). And the result is the validation error (Zend_Validate_NotEmpty::IS_EMPTYNOT_EMPTY).
Do you have any suggestions? Thanks
Hello,
Does anyone have a solution for the file field?
It always returns the max file size error and it seems to just post the file name and not the file, which is fine, but it would be nice to have some file auto detection and then ignore them.
I know a few replied with isPartialValid but I’m unsure where and when to impliment them. Atm this is my entire partial I use for forms now:
headScript()->captureStart(); ?>
$(function() {
$(‘.zend_form input, .zend_form textarea’).blur(function() {
var formElementId = ($(this).parent().prev().find(‘label’).attr(‘for’));
doValidation(formElementId);
});
});
function doValidation(id) {
var url = ‘//json/validateform/form_name/form); ?>’;
var data = {};
$(‘.zend_form input, .zend_form textarea’).each(function() {
data[$(this).attr('name')] = $(this).val();
});
$.post(url, data, function(resp) {
$(‘#’+id).parent().find(‘.errors’).remove();
$(‘#’+id).parent().append(getErrorHtml(resp[id], id));
}, ‘json’);
};
function getErrorHtml(formErrors, id) {
var o = ”;
if (formErrors != null) {
var o = ”;
for (errorKey in formErrors) {
o += ”+formErrors[errorKey]+”;
}
o += ”;
}
return o;
}
headScript()->captureEnd(); ?>
form) && $this->form->getErrorMessages()) {
echo $this->partial(‘partials/errors.phtml’, array(‘errors’ => $this->form->getErrorMessages(), ‘translate’ => $this->translate));
}
?>
errorMsg)) { ?>
errorMsg; ?>
form; ?>
And my json Controller is:
_getParam(‘form_name’);
$f = new $form_name();
$data = $this->_getAllParams();
$f->isValid($this->_getAllParams());
$f->isValidPartial($this->_getAllParams());
$json = $f->getMessages();
$this->_helper->json($json);
}
public function isValidPartial(array $data) {
unset($data['image_']);
unset($data['csrf']);
parent::isValidPartial($data);
}
}
Hi,
I’m a biginer and I have a problem, when I tab out in webbrowser I get an error in firebug:
The requested URL /index/validateform was not found on this server.
dont know where to look for help…