Orm models are tightly integrated with the Validation library which comes with a very flexible net.jkcode.jkmvc.validator.ValidateException
that helps you quickly handle validation errors from basic CRUD operations.
Validation rules are defined in the OrmMeta::rules
property. This property is the rules for each field to be executed by Validation.execute(exp:String, value:Any, binds:Map<String, Any?>)
method.
Each rule is net.jkcode.jkmvc.orm.RuleValidator
object, which has 2 properties:
label
: A label is a human-readable version of the field name.rule
: A validation expressions, split by space
There are 2 way to define rules
- override
OrmMeta::rules
property
public override val rules: MutableMap<String, IValidator> = hashMapOf(
"userId" to RuleValidator("Id label", "notEmpty"),
"age" to RuleValidator( "Age label", "digit() between(1,120)")
)
- call
OrmMeta::addRule(field: String, label:String, rule: String?)
method to add rule
// add label and rule for field
addRule("name", "Name label", "notEmpty");
addRule("age", "Age label", "digit() between(1,120)");
Jkmvc execute validation by Orm.validate()
method.
It will visit each field's rule in OrmMeta::rules
, and execute the rule on the field's value using Validation.execute(exp:String, value:Any, binds:Map<String, Any?>)
method.
The method has actual parameter:
exp
: the field's rulevalue
: the field's valuebinds
: the other fields' values
All models automatically validate their own data by calling Orm.validate()
when Orm::save()
, Orm::update()
, or Orm::create()
is called. Because of this, you should always expect these methods to throw an net.jkcode.jkmvc.validator.ValidateException
when the model's data is invalid.
public fun create()
{
try
{
val user = UserModel()
user.username = 'invalid username';
user.save();
}
catch (e: ValidateException)
{
// handle exception
}
}
```ivew