开发者

Zend Form: How to create a 'create account form' that checks for 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 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('StringTr开发者_开发技巧im'),
    'validators' => array(
        array('StringLength', false, array(2, 50)),
        array('Db_NoRecordExists', false, array(
            'table' => 'users',
            'field' => 'username'
        ))
    )
));


Add a Db_NoRecordExists validator to the form element.

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


You should be doing this check yourself server side. You shouldn't be letting the database handle this. You can then produce a nice error. You should do this regardless of any client side/ajax checks.

To do the Ajax check, create a controller that returns 0 or 1 . An easy way to bypass the view and layout code is to just exit(); at the end of the controller. When you make the Ajax call you assign a handler for the result. This handler reads the result and determine whether or not to display the message.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜