# Validation
# Introduction
ExpressWebJs makes it easy to validate user input with the help of it's validation feature, let's look at a complete example of validating a form and displaying the error messages back to the user.
# Defining The Routes
First, let's assume we have a post route defined in our Routes/api.ts file:
Route.post("post", "UserController@store");
Copied!
The POST route will store user data in the database.
# Writing The Validation Logic
To create our validation to validate user data, we do that with the Maker command
This will generate our UserValidator class in App/Http/Validation folder. If this folder is not there, it will create it for us.
Our generated UserValidator class in UserValidator_request.ts file looks like so:
import { FormRequest } from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { //validation rules. }); } }
Copied!
We can now create our validation rules in the validation rules section in validate method like so:
import { FormRequest } from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { first_name: "required|string", last_name: "required|string", phone: "required|max:14", email: "required|string|email|max:255", country: "required|string|max:255", city: "required|string|max:255", industry: "required|string|max:255", }); } }
Copied!
# Using validation in controller
We can now use our UserValidator in UserController like so:
import { UserValidator } from "App/Http/Requests/userValidator_request"; import { Request, Response, NextFunction } from "Elucidate/HttpContext"; import HttpResponse from "Elucidate/HttpContext/ResponseType"; export class UserController { store = async (req: Request, res: Response, next: NextFunction) => { try { let validate = await UserValidator.validate(req.body); if (!validate.success) return HttpResponse.BAD_REQUEST(res, validate); //continue processing your data } catch (error) { return next(error); } }; }
Copied!
# Inline validation
We can also perform inline validation in our controller like so:
import { Request, Response, NextFunction } from "Elucidate/HttpContext"; import HttpResponse from "Elucidate/HttpContext/ResponseType"; export class UserController { store = async (req: Request, res: Response, next: NextFunction) => { try { let validate = await req.validate(req.body, { first_name: "required|string", last_name: "required|string", phone: "required|max:14", email: "required|string|email|max:255", country: "required|string|max:255", city: "required|string|max:255", industry: "required|string|max:255", }); if (!validate.success) return HttpResponse.BAD_REQUEST(res, validate); //continue processing your data } catch (error) { return next(error); } }; }
Copied!
# Working With Nested Rules
Nested objects can also be validated. There are two ways to declare validation rules for nested objects. The first way is to declare the validation rules with a corresponding nested object structure that reflects the data. The second way is to declare validation rules with flattened key names. Let's say our request data looks like so:
let data = { name: "Alex", bio: { age: 27, education: { primary: "Elementary School", secondary: "Secondary School", }, }, };
Copied!
We could declare our validation rules as follows:
import { FormRequest } from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { name: "required", bio: { age: "min:18", education: { primary: "string", secondary: "string", }, }, }); } }
Copied!
# Or using flattened key names
import { FormRequest } from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { name: "required", "bio.age": "min:18", "bio.education.primary": "string", "bio.education.secondary": "string", }); } }
Copied!
# WildCards Rules
WildCards can also be validated.
import { FormRequest } from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { "users.*.name": "required", "users.*.bio.age": "min:18", "users.*.bio.education.primary": "string", "users.*.bio.education.secondary": "string", }); } }
Copied!
# Regex validation
In regex validation, the field under validation must match the given regular expression.
Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character. For each backward slash that you used in your regex pattern, you must escape each one with another backward slash.
import { FormRequest } from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { name: "required|size:3", salary: ["required", "regex:/^(?!0\\.00)\\d{1,3}(,\\d{3})*(\\.\\d\\d)?$/"], yearOfBirth: ["required", "regex:/^(19|20)[\\d]{2,2}$/"], }); } }
Copied!
# Type Checking Validation
import { FormRequest } from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { age: ["required", { in: [29, 30] }], name: [{ required_if: ["age", 30] }], }); } }
Copied!
# Custom Error Messages
If you need a specific error message and you don't want to override the default one, you can pass an override as the third argument to the make object.
import {FormRequest} from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { data, { name: "required", }, { required: "You forgot to give a :attribute" } ); } }
Copied!
If the validation fail, the error message will be 'You forgot to give a name'.
Some of the validators have string and numeric versions. You can change them too.
import {FormRequest} from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { data, { username: "max:16", }, { max: { string: "The :attribute is too long. Max length is :max.", }, } ); } }
Copied!
If the validation fail, the error message will be 'The username is too long. Max length is 16.'
You can even provide error messages on a per attribute basis! Just set the message's key to 'validator.attribute'
import {FormRequest} from "Elucidate/Validator/FormRequest"; export class UserValidator extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { data, { email: "required", }, { "required.email": "Without an :attribute we can't reach you!" } ); } }
Copied!
If the validation fail, the error message will be "Without an email we can't reach you!"
# Available Validation Rules
Below is a list of all available validation rules and their function:
Note: Validation rules do not have an implicit 'required'. If a field is undefined or an empty string, it will pass validation. If you want a validation to fail for undefined or '', use the required rule.
Rule | Function |
---|---|
accepted | The field under validation must be yes, on, 1 or true. This is useful for validating "Terms of Service" acceptance. |
after:date | The field under validation must be after the given date. |
after_or_equal:date | The field unter validation must be after or equal to the given field. |
alpha | The field under validation must be entirely alphabetic characters. |
alpha_dash | The field under validation may have alpha-numeric characters, as well as dashes and underscores. |
alpha_num | The field under validation must be entirely alpha-numeric characters. |
array | The field under validation must be an array. |
before:date | The field under validation must be before the given date. |
before_or_equal:date | The field under validation must be before or equal to the given date. |
between:min,max | The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in the same fashion as the size rule. |
boolean | The field under validation must be a boolean value of the form true, false, 0, 1, 'true', 'false', '0', '1' |
confirmed | The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input. |
date | The field under validation must be a valid date format which is acceptable by Javascript's Date object. |
digits:value | The field under validation must be numeric and must have an exact length of value. |
digits_between:min,max | The field under validation must be numeric and must have length between given min and max. |
different:attribute | The given field must be different than the field under validation. |
The field under validation must be formatted as an e-mail address. | |
hex | The field under validation should be a hexadecimal format. Useful in combination with other rules, like hex|size:6 for hex color code validation.
|
in:foo,bar,... | The field under validation must be included in the given list of values. The field can be an array or string. |
integer | The field under validation must have an integer value. |
max:value | Validate that an attribute is no greater than a given size |
min:value | Validate that an attribute is at least a given size. |
not_in:foo,bar,... | The field under validation must not be included in the given list of values. |
numeric | Validate that an attribute is numeric. The string representation of a number will pass. |
present | The field under validation must be present in the input data but can be empty. |
required | The field under validation must be present in the input data and not empty. |
required_if:anotherfield,value | The field under validation must be present and not empty if the anotherfield field is equal to any value. |
required_unless:anotherfield,value | The field under validation must be present and not empty unless the anotherfield field is equal to any value. |
required_with:foo,bar,... | The field under validation must be present and not empty only if any of the other specified fields are present. |
required_with_all:foo,bar,... | The field under validation must be present and not empty only if all of the other specified fields are present. |
required_without:foo,bar,... | The field under validation must be present and not empty only when any of the other specified fields are not present. |
required_without_all:foo,bar,... | The field under validation must be present and not empty only when all of the other specified fields are not present. |
same:attribute | The given field must match the field under validation. |
size:value | The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. |
string | The field under validation must be a string. |
url | Validate that an attribute has a valid URL format. |
regex:pattern | The field under validation must match the given regular expression. |
# Custom Validation Rules
ExpressWebJs provides a variety of helpful validation rules; however, you may wish to create some of your own custom rules. To generate your rule, you will use the make-rule
Maker command. Let's use this command to generate a rule that verifies a string is lowercase. ExpressWebJs will place the new rule in the App/Rules directory:
ts-node maker make-rule LowerCase
Copied!
Once the rule has been created, we can now define its behavior. A rule object contains two methods: passes and errorMessage. The passes method receives the attribute value, and should return true or false depending on whether the attribute value is valid or not. The errorMessage method should return the validation error message that should be used when validation fails:
import Rule from "Elucidate/Validator/Rule"; class LowerCase extends Rule { /** * Determin if the validation rule passes. * @param {string} attribute * @param {string | number | boolean} value * @returns boolean */ public passes(value: string | number | boolean): boolean { if (value.toString().toLowerCase() === value) { return true; } else { return false; } } /** * Get the validation error message * @returns string */ public errorMessage(): string { return "The :attribute must be lowercase"; } } new LowerCase();
Copied!
Once the rule has been defined, you can now attach it to a validator like so:
import FormRequest from "Elucidate/Validator/FormRequest"; import "App/Rules/LowerCase"; export class UserValidation extends FormRequest { /** * Handle the request validation. * @param {*} data | e.g request body */ static async validate<T>(data: T) { return await FormRequest.make<T>(data, { first_name: "required|string|LowerCase", }); } }
Copied!