Zend form: how to create a “create account form” that validates a unique username?

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 double username, it throws an exception. It ultimately looks pretty ugly.

I am going to do some kind of check before inserting into the database (possibly with ajax) to see if the required username has already been done. If it turns out that the username has already been completed, I want to set the user name in the form in the error field and indicate the error message that will be displayed.

How can i do this?

Update: Zend_Validator_Db_NoRecordExists works great for this kind 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' )) ) )); 
+4
source share
2 answers

Add the Db_NoRecordExists form element to the form element.

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

+5
source

You must do this by testing yourself on the server side. You must not allow the database to handle this. Then you can create a good mistake. You should do this regardless of any client / ajax checks.

To perform an Ajax check, create a controller that returns 0 or 1. An easy way to get around the view and layout code is to simply exit (); at the end of the controller. When you make an Ajax call, you assign a handler to the result. This handler reads the result and determines whether or not to show the message.

0
source

All Articles