Model Configuration
beforeValidation()
Signature
Section titled “Signature”beforeValidation() — returns void
Available in: model
Category: Callback Functions
Description
Section titled “Description”Registers method(s) that should be called before an object is validated.
Parameters
Section titled “Parameters”| Name | Type | Required | Default | Description |
|---|---|---|---|---|
methods | string | no | — | Method name or list of method names that should be called when this callback event occurs in an object’s life cycle (can also be called with the method argument). |
Examples
Section titled “Examples”// 1. Register a single method to run before any validation
// In models/User.cfc
component extends="Model" {
function config() {
beforeValidation("normalizeEmail");
validatesPresenceOf("email");
}
private function normalizeEmail() {
this.email = LCase(Trim(this.email));
}
}
// 2. Register multiple methods to run before validation using a comma-delimited list
// In models/Article.cfc
component extends="Model" {
function config() {
beforeValidation("stripTags,setSlug");
validatesPresenceOf(properties="title,slug");
}
private function stripTags() {
this.title = ReReplace(this.title, "<[^>]*>", "", "all");
}
private function setSlug() {
if (!Len(this.slug)) {
this.slug = LCase(ReReplace(Trim(this.title), "\s+", "-", "all"));
}
}
}
// 3. Register callbacks across multiple calls (they are stacked in order)
// In models/Product.cfc
component extends="Model" {
function config() {
beforeValidation("trimFields");
beforeValidation("setDefaults");
}
private function trimFields() {
this.name = Trim(this.name);
}
private function setDefaults() {
if (!Len(this.status)) {
this.status = "draft";
}
}
}