Zend_From Validator only if the field input has changed?
I'm writing a Backend System and I want to allow the users to change their email address. I've written a custom validator to check if the email-address the user has entered already exists in my database.
Now I ran into a problem: The form is populated with the user data, so his email address is the default value of the email field. Now if the user submits the form, my validators throws an error, because (of course) this email开发者_运维技巧 address does already exist!
How can I solve this problem? Maybe a Validator is not the right approach to do this? Or is there a solution to detect if the user changed the default value and fire the validator only in that case?
Hehe, that's a common problem running into validators the first time. The key is to remove that one id from the validator, inside your validator exclude the current user ID from the clause:
$validator = new Zend_Validate_Db_NoRecordExists(
array(
'table' => 'users',
'field' => 'email',
'exclude' => array(
'field' => 'id',
'value' => $id_to_edit
)
)
);
Edit: for further explanation as to what this does. It still grabs all the email adresses from the database and it still checks if there's a misconflict. If an email exists, it just ignores the email from id=$id_to_edit - so when the user changes its email but another user has that email already, the error gets thrown anyways!
精彩评论