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.

Name Type Required Default Description
methods string No Method name or list of method names to call. Can also be called with the method argument.
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).
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).
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!