Validation

KambojaJS provide a built-in validation by using TypeScript decorator, KambojaJS validation can be applied to an action parameter, model and a nested model

List of validation supported:

Validation Description
@val.required() Required validation
@val.email() Email validation
@val.range(<min>, <max>) Range validation can be specified to a string and number
@type(<qualified class name>) Reference to a model

Parameter Valiation

Validating parameter in KambojaJS is simple, you only need to use @val decorator to decorate specific parameter.

import { ApiController, val } from "kamboja-express"
import { ItemOdm } from "../model/odm"

export class ItemsController extends ApiController {

    get( @val.required() id: string) {
        return ItemOdm.findById(id).exec()
    }
}

Above code showing the id parameter of the get action decorated with a @val.required() validator. It means when the id value is not provided the validation process is fail.

Model Validation

Applying validation to model is the same, but the @val decorator applied to specific property of the model. Below example showing how to add validation rule to a model

import { val } from "kamboja-express"

export class ItemModel{
    @val.required()
    name:string

    @val.required()
    price:number

    createdAt:Date

    updatedAt:Date
}

Above code showing the name and price field is mandatory by adding @val.required().

To make a model validation work properly, you need to specify the qualified class name of the model in the appropriate action parameter:

import { ApiController, val } from "kamboja-express"
import { ItemModel } from "../model/item-model"
import { ItemOdm } from "../model/odm"

export class ItemsController extends ApiController {

    add( @type("ItemModel, model/item-model") model: ItemModel) {
        let odm = new ItemOdm(model)
        return odm.save()
    }
}

Above code showing that we register the validation to a model using @type() decorator and provide the model qualified class name. Using that setup validation system will understand where should find the validation rule to validate the model.

Validation on Nested Model

KambojaJS validation can be use to validate a nested model by specify the qualified class name of the child model.

import { val } from "kamboja-express"
import { CategoryModel } from "model/category-model"

export class ItemModel{
    @val.required()
    name:string

    @val.required()
    price:number

    @type("CategoryModel, model/category-model")
    category:CategoryModel

    createdAt:Date

    updatedAt:Date
}

Above code showing that we adding a category field which is the parent of the item, then specify the qualified class name of the CategoryModel using @type() decorator.

Auto Response Validation

KambojaJs will send response for fail validation automatically. It will return 400 Http Status with some Validation Message when request body/parameter doesn’t match with model validation rule.

Note you can disable this feature globally by setting autoValidation:false on Kamboja instance. Then you can check the validation manually by calling this.validator.isValid() and calling this.validator. getValidationErrors() inside the controller itself

Custom Validation

If you require more validator than the provided, you can create your own logic by extending ValidatorBase class.

For example we will created a custom validation to validate a Mongodb id, usually we do that by using Mongoose ObjectId.isValid function

import { Validator, Core } from "kamboja-express"
import { Types } from "mongoose"
import * as Kecubung from "kecubung"

//decorator will be applied on parameter/model
export function objectid(customMessage?: string) {
    return (...args) => { }
}

//validation logic will be registered in KambojJs application
export class MongodbIdValidator extends Validator.ValidatorBase {

    @Validator.decoratorName("objectid")
    validate(args: Core.FieldValidatorArg) {
        if (this.isEmpty(args.value)) return
        if (!Types.ObjectId.isValid(args.value.toString())) {
            //get first decorator parameter (customMessage)
            let argument = <Kecubung.PrimitiveValueMetaData>args.decoratorArgs[0]
            let customMessage = argument && argument.value
            return [{
                field: args.parentField ? `${args.parentField}.${args.field}` : args.field,
                message: customMessage || `[${args.field}] is not a valid email address`
            }]
        }
    }
}

Above code showing separate code when creating a custom validator, the decorator and the validator logic. Decorator will mark specific field/parameter that will be validated, the validator will validate and return the validation message.

To use validator above you need to register the validator in KambojaJs application like below:

let kamboja = new Kamboja(new ExpressEngine(), {
    rootPath: __dirname,
    validators: [
        new MongodbIdValidator()
    ]
})

That’s it, with above code your validator registered to the KambojaJS application.

Note you can also register the validator with qualified class name. The validator option is receiving a string value or a ValidatorBase instance.