Let’s talk about what happens when a user signs up for a new account. He fills in his nickname, e-mail address and password and clicks Register. When validating the e-mail address you need to check for at least three things:
- the user provided one
- the syntax is all right – the e-mail is formally valid and can in fact exist (which doesn’t mean it really exists)
- the address hasn’t been used yet for some other account
So far not very difficult.
The tricky part comes when you allow the user to edit his profile. He can change any of the three values. When he submits the edit form the situation is one step more difficult than during registration. The e-mail address has in fact already been used – for the very user that is submitting the form. That is not the tricky part. The fun is how to get the user id when validating his e-mail address.
Without further ado, here’s the code:
(using NotORM initiated in BaseModel constructor)
-
span class=”st0″>’email’, ‘E-mail:’‘Please provide your e-mail address.’"Sorry, this doesn’t seem to be a valid e-mail address.")
-
->addRule(‘BaseModel::uniqueEmail’, ‘This e-mail is already registered.’‘id’// —————————————————————-
-
’email’// Test for any record with given e-mail address
-
‘id’"*") == 0);
-
}
-
-
// Test for any record with given address – that isn’t this record
-
‘NOT id’, $values[‘id’"*") == 0);
-
}
-
Tags: Nette Framework 2.0-beta (revision 8a3182e released on 2011-10-11)
Why is the `uniqueEmail` method in class BaseModel? I’d like more
->addRule(callback($usersModel, ‘uniqueEmail’), ‘This e-mail is already registered.’);
True. It can be in any model/class. In my case, I used this validation for more than one model (not visible in the code above) so I placed it in a shared BaseModel.
Thanks for the example of using callback with an instance of some class. If you happen to need an instance anyway, in your component/form factory then you can use it for the callback and get rid of instantiating the object in the method itself ($me = new self).