Description | Validates values using a schema. |
Language | Actionscript 3 |
Source | http://github.com/headjump/valuedate |
// chained validation var my_value:int = 15; Assure.value.isA(Number).inRange(10, 20).validate(my_value); // => true // validating Object structure (with optional properties) // Test objects var admin:Object = { role: "admin", info: { title: "I'm admin" } }; var user:Object = { role: "user" }; var mother:Object = { role: "your mother", age: 88 }; // Validation schema var schema:Assure = Assure.value.forProperties( { role: Assure.value.equalsOneOf("admin","user"), info: Assure.optional_value.forProperties( { title: Assure.value.isA(String) }) }); // Validating... schema.validate(admin); // => true schema.validate(user); // => true schema.validate(mother); // => false
Add a function in Assure.as to the Assure
class, following this template:
Template
public function myFunction(my_params):Assure { return check(function(value:*) { // here goes your code! // @value is the value to validate // if @value matches your constraints: do nothing // otherwise: throw an Error! }); }
The validate(...)
function you call to validate a value catches your errors. If there are any, it returns false
, otherwise true
.
So all you have to do is throw an Error
if your constraints are violated.
Example
public function isA(c:Class):Assure { return check(function(value:*) { if (!(value is c)) throw new Error("!ofClass " + [value, c]); }); }