Web · real, tested code

Validate a Web Form Submission in Larzscript

Validate a whole submitted record against a schema at once - required fields, ranges, and an allowed-choices list - with automatic type coercion.

validate.field() describes one field's rules; validate.validate_schema() checks every field in one pass and returns both the coerced data and a list of every error found, not just the first one.

larzscript pkg install validate

Code

import "validate" as validate

let s = validate.schema({
  "name": validate.field("string", true, nil, nil, nil, nil),
  "age": validate.field("number", false, 0, 150, nil, nil),
  "role": validate.field("string", true, nil, nil, nil, ["admin", "user"])
})
let good = validate.validate_schema({"name": "Ada", "age": "36", "role": "admin"}, s)
print(good["valid"], good["data"]["age"])
let bad = validate.validate_schema({"name": "Ada", "role": "superuser"}, s)
print(bad["valid"], bad["errors"])
Output
true 36
false [role must be one of [admin, user]]