Thursday, November 4, 2010

Validate Model: User

Rule 1: Never trust user input
Rule 2: When in doubt, see rule 1

For every model you should create a validate variable which will be used to validate input fields. For our user model we need to verify that username and email are unique on creation.

Since validation can be quite complex, building the validation variable one field at a time can be helpful. For full details on data validation see http://book.cakephp.org/view/1143/Data-Validation

Edit /app/models/user.php and add
    var $validate = array(
        'username' => array(
            'alphanumeric' => array(
                'rule' => '/^[a-z0-9]{3,}$/i',
                'required' => true,
                'message' => 'Username must contain only letters and numbers.'
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'message' => 'This username is already taken.'
            ),
            'minlength' => array(
                'rule' => array('minlength', 5),
                'message' => 'Username must be at least 5 characters.'
            ) 
        )
    );
Upload the file then browse to http://drug-ed.com/users/add and observe how the "Username" field label is bolded and followed by a red asterisk helping to identify the required aspect of that field. Test your validation rule by trying a 2 letter username, or one composed of special characters.

Now that you are sure that field validation is working properly, add the next field. Edit /app/models/user.php and add at the end of the validate array
        ),
        'email' => array(
            'email' => array(
                'rule' => 'email',
                'required' => true,
                'message' => 'You must enter a valid email address.'
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'on' => 'create',
                'message' => 'This email address is already on record.'
            )
        )
    );
Notice the line 'on' => 'create' in the email validation. When editing a user the isUnique rule will fail because the user's email is already in the database! Changing it to only verify when you create an new user will prevent this problem.

Upload the file then browse to http://drug-ed.com/users/add to again verify it works as intended.

No comments:

Post a Comment