Contact Us

Making two form fields required to match each other

Posted on 25/3/07 by Tim Koschützki

Deprecated post

The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.

Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.

Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).

It is common in web application that you want to force two form fields to match each other. Often this is used for a new user having to register with your site - the two fields for his password have to match. This is a simple way of preventing the user to misstype his password and then be not able to login to the site, causing another registration and a "data corpse".

In cake php this can be easily achieved.

Defining a small function in your App Model - /cake/app_model.php

function isConfirm($field,$v1,$v2) {
        if($v1 != $v2) {
            return false;
        } else  return true;

As you can see this function takes three parameters - the form fields name, the form fields value and the value of the confirmation form field. The confirmation form field has to have the name of the original form field prefixed with 'confirm_' for this to work.

So what does your view look like?

In your form type in the following html code, or similar code that suits your needs:

  <?php echo $html->password('Member/password');?>
  <label>Confirm Password</label>
  <?php echo $html->password('Member/confirm_password');?>

Making it all work - in the controller

In your controller you can now type:

if(!empty($this->data['Member'])) {
    $this->data['Member']['password'],$this->data['Member']['confirm_password']) {

be aware of the unset() call there. This is necessary, because you don't to save the confirm_password field to your database.


You could have simply compared the two values directly in the controller. However, you would have needed to call Model->invalidate() then on the confirm_ field everytime. The simple isConfirm() function does that for you. What is not so nice is the need to call unset() before saving the form. One should be able to access the form data in the model, too, for this code to become really neat.

However, wouldn't that be break the MVC principle?


You can skip to the end and add a comment.

Yevgeny Tomenko (aka SkieDr)  said on Sep 10, 2007:

Good idea. It need to include sych convention to core :)

This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.