Using Default Values
Using default values in constraints
The defaultValue constraint (introduced in 4.5.0) allows you to automatically apply default values to fields before validation rules are checked. This is useful for initializing optional fields with sensible defaults.
Overview
When a field has a defaultValue defined and the field's current value is null or empty, the default value will be assigned to the field before any other constraints are evaluated.
Basic Usage
class {
this.constraints = {
status: {
defaultValue: "active",
required: true,
inList: "active,inactive,pending"
},
createdDate: {
defaultValue: now(),
required: true,
type: "date"
},
priority: {
defaultValue: 5,
min: 1,
max: 10
}
};
}component {
this.constraints = {
status: {
defaultValue = "active",
required = true,
inList = "active,inactive,pending"
},
createdDate = {
defaultValue = now(),
required = true,
type = "date"
},
priority = {
defaultValue = 5,
min = 1,
max = 10
}
};
}When Defaults Are Applied
The defaultValue is applied when:
The field value is null
The field value is an empty string (for simple values)
The field value has no value (hasValue() check fails)
The default is NOT applied when:
The field already has a non-empty value
The field is explicitly set to a falsy value like
falseor0
Practical Examples
Form with Default Status
In your handler:
Dynamic Default with Functions
You can use closures to compute dynamic defaults:
API Validation with Defaults
Best Practices
1. Use for Optional Fields Only
Default values work best for truly optional fields:
2. Defaults Should Match Constraint Rules
Always ensure your default value complies with other constraints:
3. Use Functions for Dynamic Defaults
For timestamp or unique identifier defaults, use functions:
4. Document Default Behavior
Always document which fields have defaults:
See Also
Constraint Profiles - Validate different field sets for different scenarios
Custom Constraints - Customize validation messages
Validating Constraints - Main validation documentation
Last updated
Was this helpful?