Skip to content

Latest commit

 

History

History
60 lines (45 loc) · 2.04 KB

validation.md

File metadata and controls

60 lines (45 loc) · 2.04 KB

Validation

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.

1 Defining Rules

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:

  1. label: A label is a human-readable version of the field name.
  2. rule: A validation expressions, split by space

There are 2 way to define rules

  1. 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)")
)
  1. 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)");

2 Execute validation

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:

  1. exp: the field's rule
  2. value: the field's value
  3. binds: the other fields' values

3 Automatic Validation

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