Skip to content

Model Configuration

validatesUniquenessOf()

validatesUniquenessOf() — returns void

Available in: model Category: Validation Functions

Validates that the value of the specified property is unique in the database table. Useful for ensuring that two users can’t sign up to a website with identical usernames for example. When a new record is created, a check is made to make sure that no record already exists in the database table with the given value for the specified property. When the record is updated, the same check is made but disregarding the record itself.

NameTypeRequiredDefaultDescription
propertiesstringno—Name of property or list of property names to validate against (can also be called with the property argument).
messagestringno[property] has already been takenSupply a custom error message here to override the built-in one.
whenstringnoonSavePass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
allowBlankbooleannofalseIf set to true, validation will be skipped if the property value is an empty string or doesn’t exist at all. This is useful if you only want to run this validation after it passes the validatesPresenceOf test, thus avoiding duplicate error messages if it doesn’t.
scopestringno—One or more properties by which to limit the scope of the uniqueness constraint.
conditionstringno—String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unlessstringno—String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
includeSoftDeletesbooleannofalseSet to true to include soft-deleted records in the queries that this method runs.
// 1. Ensure no two users share the same username
validatesUniquenessOf(property="username", message="Sorry, that username is already taken.");

// 2. Scope uniqueness to an account — the same username is allowed in different accounts
validatesUniquenessOf(property="username", scope="accountId");

// 3. Validate multiple properties for uniqueness in one call
validatesUniquenessOf(properties="email,username");

// 4. Skip the check when the email field is blank (pair with validatesPresenceOf to avoid duplicate errors)
validatesUniquenessOf(property="email", allowBlank=true);

// 5. Only enforce uniqueness on create, not on update
validatesUniquenessOf(property="slug", when="onCreate");

// 6. Run the check only when a condition is true
validatesUniquenessOf(property="referralCode", condition="this.isAffiliate()");

// 7. Include soft-deleted records in the uniqueness check so a previously-deleted value stays reserved
validatesUniquenessOf(property="username", includeSoftDeletes=true);