There are 7 basic concepts that are used in Koa Validation

Field Names

The naming conventions for the fields being validated or filtered on are quite simple. The validation blocks are Javascript objects and the object keys are typically the field names themselves. For eg.

If you need to validate a fields named gender and email, they would be written as:

{
    gender:'in:male,female'
    email: 'required|email'
}

There are times when you need to validate nested fields and arrays. Koa Validation can handle those too. Within the key names separate the nested elements with a "."

So if you are looking to validate an array like ['fox', 'rabbit', { 'king': 'Lion' }]

{
    'array.0': 'required|in:fox,wolf,dog',
    'array.1': 'requiredIf:array.1,fox',
    'array.2.king': 'match:Lion'
}

Required Rules

Required Rules determine whether a field is mandatory or not. In the absence of a required rule, the field will be considered optional and will only be validated against other rules if the field exists.

Required rules are typically prefixed with a required and decide the field necessity based on conditions. More on required rules is covered later.

{
    email: 'required|email',
    name: 'requiredWith:email',
    password: 'requiredIf:email,[email protected]'
}

Field Rules

Koa Validation has a host of rules that can be applied to validate fields sent over a request. Field rules are declared as value to the keys. They can either be declared as strings or objects.

Also some field rules could have additional arguments. Given Below are some rules declared as strings. Each rule is separated by a "|" and arguments to the rule are passed by using a ":" after the rule name and passing comma separated values.

{
    gender: 'in:male,female',
    email: 'email|string|required',
    smallNumber: 'digitsBetween:10,100'
}

To pass the field rules as objects, pass the rule name as the object key and arguments as an array of values. The same rules declared above would be written as:

{
    gender: { in: ['male', 'female'] },
    email: { email: [], string: [], required: [] },
    smallNumber: { digitsBetween: [10, 100] }
}

File Rules

Koa Validation also provides a way to validate files coming in through multipart/form-data.

This feature has only been tested against the koa-better-body module. Hence other koa middlewares parsing multipart data may not work. The file rules work exactly as the field rules and are declared in the very same way. File rules like field rules can be declared as both strings and objects.

{
    'jsFile':{ required: [], size:['min','10kb','max','20kb'] },
    'imgFile': 'required|image',
    'imgFile1': 'mime:jpg',
}

Field Filters

Filters are a way to allow you to change the state of the input data before or after performing the validation. It could be a very handy tool to perform minor operations like trimming strings or converting them to lower cases or even performing a hex operation on them to compare passwords from the database.

Filters are declared in pretty similar manner to rules except they are purely declared as strings and not arrays. The filters object consists of the field name as key and the filter name as value. Multiple filters per field can be declared and each filter is separated by a "|". Arguments are passed to the filter by using the ":" after the filter name and passing arguments as comma separated values.

Filters can be performed both before and after the validation. Hence the filters need to be passed within the before and after keys within the filters object.

{
    before: {
        name: 'lowercase',
        nickname: 'uppercase',
        snum: 'integer',
        sword: 'trim',
        lword: 'ltrim',
        rword: 'rtrim',
        dnum: 'float',
        bword: 'boolean'
    },
    
    after: {
        obj: 'json',
        eword: 'escape',
        reword: 'replace:come,came',
        shaword: 'sha1',
        mdword: 'md5',
        hexword: 'hex:sha256'
    }
}

File Actions

File Actions are performed on the files after the validations on them have been performed. The file actions are declared as an object or an array of objects where the key is the name of the object and the value is an object with the keys action, args and callback.

{
    jsFile: {
        action: 'move',
        args: __dirname + '/../files/tmp/rules.js',
        callback: function *(validator, file, destination){
            validator.addError(jsFile, 'action', 'move', 'Just checking if the callback action works!!')
        }
    },
    imgFile: [
        {
            action: 'copy',
            args: __dirname + '/../files/tmp/panda.jpg'
        },
        {
            action: 'delete'
        }
    ]
}

The action field contains the name of the action, the args field is optional and depends upon the action being performed. The callback field is a generator function that can be optionally performed after the completion of the file action. The code above summarizes the file action object.

Custom Validation Messages

Custom Validation messages are used to change the default validation messages thrown by the validation methods. Custom error messages can also have placeholders. Placeholders are used to print the field name, arguments or value of the field. The :value and :attribute place holders are available to all rules. Other placeholders are also available on specific rules.

{
    "name": "There was a problem with the name field",
    "name.required": "The name field is mandatory",
    "age.digitsBetween": "The age of the candidate must be between :min and :max",
    "email": "The :attribute was improperly entered or left empty"
}

When a field name is used without being prefixed with a rule, all errors will return the same error. However, when the field name is followed by a "." and the rule, the message will apply in case the field errors with that specific rule. Example of the same can be seen above.