Zend Form: How to create a 'create account form' that checks for unique username?

ajax, jquery, zend-form, zend-framework

Solution

Add a `Db_NoRecordExists` validator to the form element.

http://framework.zend.com/manual/en/zend.validate.set.html#zend.validate.Db

Problem

I have a form where a user can create an account. The username column is unique in the database. If a user tries to create an account with a duplicate username, it throws an exception. This ends up looking pretty ugly. I'm thinking about doing some sort of check before inserting in the database (possibly with ajax) to see if the desired username has already been taken. If it turns out the username has already been taken, I want to set the username field on the form in an error state and specify an error message to be displayed. How can I do this? Update: `Zend_Validator_Db_NoRecordExists` works great for this sort of thing. Here is what I ended up with: ``` // inside my create account form $this->addElement('text', 'username', array( 'label' => 'Username:', 'required' => true, 'filters' => array('StringTrim'), 'validators' => array( array('StringLength', false, array(2, 50)), array('Db_NoRecordExists', false, array( 'table' => 'users', 'field' => 'username' )) ) )); ```

Original source