validify
validify is a Validation Class that helps you to validate your incoming data
Examples
Initialize
import Validation, {ErrorMessages, Fields, Rules} from "https://deno.land/x/validify@v0.0.2/mod.ts";
const validation = new Validation()
Custom error messages
const customErrorMessages: ErrorMessages = JSON.parse(Deno.readTextFileSync("./en.json"))
/*
{
"required": "The {field} field is required.",
"email": "The {field} field must contain a valid email address.",
"url": "The {field} field must contain a valid URL.",
"ip": "The {field} field must contain a valid IP.",
"min": "The {field} field must be at least {param} in length.",
"max": "The {field} field cannot exceed {param} in length.",
"size": "The {field} field must be exactly {param} in length.",
"in": "The {field} field must be one of: {param}.",
"string": "The {field} must be a text.",
"number": "The {field} field must be an number.",
"array": "The {field} field must be an array."
}
*/
const validation = new Validation(customErrorMessages)
If you don't pass custom error messages object the errors will look like this by default:
There is an error in field: {field}**
validate, single, getErrors
// Data to validate
const input = {
name: 'Doğukan Akkaya',
email: 'info@codethereal.com',
url: 'codethereal.com',
address: [
{
name: 'Address line 1',
location: 'Turkey, Istanbul'
},
{
name: 'Address line 2',
location: 'Turkey, Istanbul'
}
],
detail: {
job: 'Software Developer',
salary: 10.000,
currency: 'USD'
},
status: 1,
numbers: [1,2,3,4,5,6]
}
// Rules to apply
const rules: Rules = {
name: 'string|required|max:25|min:5',
email: 'string|required|email',
url: 'string|required|url',
address: {
name: 'string|required',
location: 'string|required'
},
detail: {
job: 'string',
salary: 'number',
currency: 'string|in:USD,EUR,TRY'
},
status: 'number|required|in:0,1',
numbers: 'required|array|max:5'
}
// Errored fields name to show prettier messages to user
const fields: Fields = {
name: 'Name',
email: 'Email',
address: {
name: 'Address Name',
location: 'Address Location'
},
detail: {
job: 'Job',
salary: 'Salary',
currency: 'Currency'
},
}
// Run `validate` with arguments and chain more data if you want with `single` function and then get the errors at last with `getErrors`
const errors = validation
.validate(input, rules, fields)
.single('name surname', 'min:5|required', 'The Name')
.getErrors()
// Check for any errors
if (errors.length > 0) {
console.log(errors)
/*
[
"The url field must contain a valid URL.",
"The numbers field cannot exceed 5 in length.",
"The test field must be at least 5 in length."
]
*/
} else {
console.log('There is no error')
}