Back

validatesPresenceOf()

Ensures that the specified property (or properties) exists and is not blank. It is commonly used to enforce required fields before saving an object to the database.

Name Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
message string No [property] can't be empty Supply a custom error message here to override the built-in one.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
1. Ensure the `emailAddress` property is not blank
validatesPresenceOf("emailAddress");

2. Ensure multiple properties are present
validatesPresenceOf("firstName,lastName,emailAddress");

3. Use a custom error message for missing email
validatesPresenceOf(
    property="emailAddress",
    message="Email is required to create your account."
);

4. Validate only on create, not on update
validatesPresenceOf(
    properties="password",
    when="onCreate",
    message="Password is required when registering a new user."
);

5. Conditional validation based on a method
validatesPresenceOf(
    properties="discountCode",
    condition="this.isOnSale()",
    message="Discount code must be present for sale items."
);
Copied!