Back
addError()
Adds a custom error to a model instance. This is useful when built-in validations don’t fully cover your business rules, or when you want to enforce conditional logic. The error will be attached to the given property and can later be retrieved using functions like errorsOn() or allErrors().
1. Add a simple error
// In app/models/User.cfc
this.addError(
property="email",
message="Sorry, you are not allowed to use that email. Try again, please."
);
Adds an error on the email property.
2. Add an error with a name identifier
this.addError(
property="password",
message="Password must contain at least one special character.",
name="weakPassword"
);
Adds a weakPassword error on the password property.
Later you can check for it:
if (user.hasError("password", "weakPassword")) {
// Handle specifically the weak password case
}
3. Adding multiple errors to the same property
this.addError(property="username", message="Username already taken.", name="duplicate");
this.addError(property="username", message="Username cannot contain spaces.", name="invalidChars");
Two different errors on username, each distinguished by their name.
4. Conditional custom errors
// Suppose only company emails are allowed
if (!listLast(this.email, "@") == "company.com") {
this.addError(
property="email",
message="Please use your company email address.",
name="invalidDomain"
);
}
Custom rule ensures only company domain emails are accepted.
5. Combine with built-in validations
// Inside a callback
function beforeSave() {
if (this.age < 18) {
this.addError(property="age", message="You must be at least 18 years old.");
}
}
Even though validatesPresenceOf("age") might exist, addError() gives you extra conditional control.
Copied!