Validation Functions
Schema-based validation with the V class and chainable validators.
Type Validators
V.string()
Validate string values
V.int()
Validate integer values
V.float()
Validate float values
V.bool()
Validate boolean values
V.array(schema?)
Validate arrays with optional item schema
V.hash(schema?)
Validate hashes with optional nested schema
Chainable Methods
Presence
.required()
Field must be present
.optional()
Field may be absent
.nullable()
Field may be null
.default(value)
Default value if absent
Constraints
.min(n)
Minimum value/length
.max(n)
Maximum value/length
.pattern(regex)
Match regex pattern
.email()
Valid email format
.url()
Valid URL format
Validate Function
validate(data, schema)
Validate data against a schema.
Parameters
data : Hash - The data to validateschema : Hash - Schema with field validatorsReturns
Hash - { "valid": Bool, "data": Hash, "errors": Array }
let schema = {
"name": V.string().required().min(2).max(100),
"email": V.string().required().email(),
"age": V.int().optional().min(0).max(150),
"website": V.string().optional().url()
}
let result = validate({
"name": "Alice",
"email": "[email protected]",
"age": 30
}, schema)
if result["valid"] {
println("Data is valid!")
println(result["data"]) // Validated & sanitized data
} else {
for error in result["errors"] {
println(error["field"] + ": " + error["message"])
}
}
Examples
User Registration
let user_schema = {
"username": V.string().required().min(3).max(20).pattern("^[a-zA-Z0-9_]+$"),
"email": V.string().required().email(),
"password": V.string().required().min(8),
"age": V.int().optional().min(13),
"newsletter": V.bool().default(false)
}
fn register(params: Hash) -> Hash {
let result = validate(params, user_schema)
if !result["valid"] {
return { "error": result["errors"] }
}
// Create user with validated data
let user = User.create(result["data"])
return { "user": user }
}
Nested Validation
let order_schema = {
"customer": V.hash({
"name": V.string().required(),
"email": V.string().required().email()
}),
"items": V.array(V.hash({
"product_id": V.int().required(),
"quantity": V.int().required().min(1)
})).min(1)
}