Back
validate()
Used to register one or more validation methods that will be executed on a model object before it is saved to the database. This allows you to define custom validation logic beyond the built-in validations like presence or uniqueness. You can also control when the validation runs (on create, update, or both) and under what conditions using condition and unless.
1. Register a method to validate objects before saving
function config() {
validate("checkPhoneNumber");
}
function checkPhoneNumber() {
// Make sure area code is '614'
return Left(this.phoneNumber, 3) == "614";
}
2. Register multiple validation methods
function config() {
validate("checkPhoneNumber, checkEmailFormat");
}
function checkEmailFormat() {
// Ensure email contains '@'
return Find("@", this.email);
}
3. Conditional validation using `condition`
function config() {
// Only validate phone numbers if the user is in the US
validate("checkPhoneNumber", condition="this.country == 'US'");
}
4. Skip validation under certain conditions using `unless`
function config() {
// Skip phone number validation if the user is a guest
validate("checkPhoneNumber", unless="this.isGuest");
}
5. Run validation only on create or update
function config() {
// Validate email only when creating a new record
validate("checkEmailFormat", when="onCreate");
// Validate password only on update
validate("checkPasswordStrength", when="onUpdate");
}
Copied!