Scriptbaker
SCRIPTBAKERAI & Software Engineering
Yii

Yii password, repeat password fields

Learn how to validate password and repeat password fields in Yii 1.1 using the compare validator, scenarios, and secure password hashing.

· 5 min read · By Tahir Yasin

When building a registration or password-change form, asking users to enter their password twice can help prevent typing mistakes. Yii 1.1 provides a built-in compare validator that checks whether two model attributes contain matching values.

In this guide, you will learn how to create a repeat password field, configure validation rules, handle different form scenarios, and store passwords securely in a Yii 1.1 application.

Why Use a Repeat Password Field?

A password confirmation field asks users to enter the same password twice. If the values do not match, the application can display a validation error before saving the account.

This approach is useful for:

  • User registration forms.
  • Password-change forms.
  • Account recovery forms that allow users to choose a new password.

The repeat password value is only needed for validation. It does not need to be stored in the database as a separate password field.

How the Yii Compare Validator Works

Yii 1.1 includes the CCompareValidator class, available through the built-in compare validator alias. It compares one model attribute with another and checks whether their values satisfy the configured comparison operator.

For a password confirmation field, the compareAttribute option identifies the attribute containing the confirmation value.

For example:

array(
    'password',
    'compare',
    'compareAttribute' => 'repeat_password',
    'message' => 'Passwords do not match.'
),

This rule checks whether the password and repeat_password attributes match. It does not check password strength or store the password securely; those responsibilities require separate rules and password-handling logic.

Official documentation: Yii 1.1 CCompareValidator API.

Step 1: Add a Repeat Password Attribute to the Model

In Yii 1.1, a model extending CActiveRecord typically represents a database record. Since repeat_password is a form-only field, declare it as a public model property rather than adding a database column for it.

class User extends CActiveRecord
{
    public $repeat_password;

    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return 'users';
    }
}

The repeat_password property can now receive form input and participate in validation without being a column in the users table.

Step 2: Configure Password Validation Rules

The rules() method defines how Yii validates model attributes. For a registration form, you can require both password fields, enforce a length range, and compare the two values.

public function rules()
{
    return array(
        array('username', 'required'),
        array(
            'password, repeat_password',
            'required',
            'on' => 'create'
        ),
        array(
            'password, repeat_password',
            'length',
            'min' => 8,
            'max' => 128,
            'on' => 'create'
        ),
        array(
            'password',
            'compare',
            'compareAttribute' => 'repeat_password',
            'message' => 'Passwords do not match.',
            'on' => 'create'
        ),
        array('username', 'length', 'max' => 60),
        array('username', 'unique'),
        array('id, username', 'safe', 'on' => 'search'),
    );
}

Important: This example applies password validation to the create scenario. The minimum and maximum lengths are example application settings, not requirements imposed by Yii itself. Choose limits appropriate for your application and password-storage implementation.

Do not add a second, overlapping password-length rule without a specific reason. Conflicting minimum values can make the code confusing and harder to maintain.

Step 3: Set the Correct Validation Scenario

Yii 1.1 supports validation scenarios, allowing different rules to run during registration, profile editing, and password changes.

For example, a new user needs to provide a password, while a user editing their username may not need to change an existing password.

// Create a new user with the registration scenario.
$user = new User('create');

// Populate the model with submitted form values.
$user->attributes = $_POST['User'];

// Validate the submitted values.
if ($user->validate()) {
    // Continue with secure password handling and saving.
} else {
    // Display validation errors.
}

For password changes, define a separate scenario such as changePassword and apply the required, length, and compare rules to that scenario. Make sure your controller explicitly selects the appropriate scenario before validating the form.

For a profile-editing form, do not require a new password unless the user has chosen to change it.

Step 4: Add Password and Confirmation Fields to the Form

Use Yii's CActiveForm helper to render the password fields and validation messages.

<?php $form = $this->beginWidget('CActiveForm', array(
    'id' => 'user-form',
    'enableAjaxValidation' => false,
)); ?>

<div class="row">
    <?php echo $form->labelEx($model, 'password'); ?>
    <?php echo $form->passwordField($model, 'password'); ?>
    <?php echo $form->error($model, 'password'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model, 'repeat_password'); ?>
    <?php echo $form->passwordField($model, 'repeat_password'); ?>
    <?php echo $form->error($model, 'repeat_password'); ?>
</div>

<div class="row buttons">
    <?php echo CHtml::submitButton('Create Account'); ?>
</div>

<?php $this->endWidget(); ?>

The password inputs use passwordField() so the browser masks the entered characters. The error() helper displays validation errors associated with the corresponding model attribute.

Client-side validation can improve the user experience, but server-side validation must remain enabled. Never rely on JavaScript alone to validate passwords.

Step 5: Store Passwords Securely

Password confirmation and password storage are separate concerns. Matching values do not make a password safe to store in plain text or with an outdated hash algorithm.

A legacy example that uses md5() to hash passwords should be replaced. MD5 is not suitable for password storage because it is too fast and lacks the protections expected from a modern password-hashing algorithm.

In PHP environments that support it, use password_hash() to create password hashes and password_verify() to check a submitted password during authentication.

// Hash a validated password before storing it.
$passwordHash = password_hash($plainPassword, PASSWORD_DEFAULT);

// Verify a password during login.
if (password_verify($submittedPassword, $storedHash)) {
    // Password is correct.
} else {
    // Reject the login attempt.
}

In a real Yii application, integrate this logic into the model or service responsible for password management. Hash the plain-text password only when creating an account or intentionally changing its password. Do not hash the existing stored hash again when a user edits an unrelated profile field.

Ensure the database column can hold the complete hash produced by your PHP configuration. A column of at least 255 characters is a practical choice for accommodating changes to the default password-hashing algorithm.

For legacy PHP installations that do not provide password_hash() and password_verify(), consider upgrading PHP or using a reputable, maintained compatibility implementation. Do not fall back to plain-text passwords or MD5.

Common Mistakes to Avoid

  • Forgetting the model property: Declare public $repeat_password; when the confirmation field is not a database column.
  • Comparing the wrong attributes: Make sure compareAttribute points to the confirmation field.
  • Using conflicting validation rules: Keep password length limits consistent and avoid redundant rules.
  • Requiring passwords on every form: Use scenarios so profile updates do not unintentionally require a new password.
  • Storing the confirmation value: Do not persist repeat_password as a password or database field.
  • Using MD5 for password storage: Replace fast, general-purpose hashes with PHP's password-hashing functions.
  • Skipping server-side validation: Validate submitted data on the server even when client-side validation is enabled.
  • Rehashing an unchanged password: Hash only a newly supplied plain-text password, not a hash already stored in the database.

Frequently Asked Questions

How do I compare two password fields in Yii 1.1?

Use the built-in compare validator and set compareAttribute to the name of the confirmation attribute, such as repeat_password.

Does repeat_password need a database column?

No. Declare it as a public property on the model if it is only used to collect and validate form input.

Can I make password confirmation optional when updating a profile?

Yes. Use validation scenarios to require and compare passwords only during registration or an intentional password-change operation. Your controller must also handle blank password submissions without overwriting the existing password hash.

Is the Yii compare validator enough to secure passwords?

No. The compare validator checks whether values match. You must separately enforce your password policy, use secure password hashing, protect authentication workflows, and validate input on the server.

Should I use MD5 to hash passwords in Yii?

No. MD5 is not recommended for password storage. Use password_hash() and password_verify() in supported PHP environments.

Conclusion

Yii 1.1 makes password confirmation straightforward through its built-in compare validator. By declaring a form-only confirmation attribute, configuring scenario-specific validation rules, and rendering the fields with CActiveForm, you can prevent common password-entry mistakes.

For a secure implementation, keep password confirmation separate from password storage and use modern password-hashing functions rather than MD5. These improvements make legacy Yii applications easier to maintain and better aligned with current password-security practices.

Official References

Last updated:

Work with Scriptbaker

Let's talk about your project

Whether you're extending an existing platform, modernising legacy code, or planning something new, our engineers can help. Tell us what you're working on and we'll explore a practical technical solution together.