What is Valkey?

Valkey is an open-source library designed for efficient data validation and transformation in JavaScript. It simplifies the process of handling and validating user inputs, ensuring data integrity and consistency. This article will guide you through getting started with Valkey, including installation, basic usage, and practical examples.

Valkey is a powerful and flexible validation library for JavaScript. It provides a set of functions to define validation schemas and perform validations against those schemas. Valkey helps developers ensure that data conforms to expected formats and types, reducing bugs and errors in applications.

Installation

To get started with Valkey, you need to install it using npm (Node Package Manager). Run the following command to install Valkey in your project:

bash
npm install valkey

If you’re using yarn, you can install it with:

bash
yarn add valkey

Basic Usage

Once Valkey is installed, you can start using it to define validation schemas and validate data. Here’s a basic example to illustrate how Valkey works:

Defining a Schema

A schema in Valkey is a blueprint for what the data should look like. Here’s an example of defining a schema:

javascript

const { valkey } = require('valkey');

const userSchema = valkey.object({
name: valkey.string().required(),
email: valkey.string().email().required(),
age: valkey.number().integer().positive().required(),
});

In this schema, we define an object with three properties: name, email, and age. Each property has specific validation rules:

  • name must be a string and is required.
  • email must be a string, formatted as an email address, and is required.
  • age must be a positive integer and is required.

Validating Data

With the schema defined, we can now validate data against it:

javascript
const userData = {
name: 'John Doe',
email: 'john.doe@example.com',
age: 30,
};
const validationResult = userSchema.validate(userData);if (validationResult.error) {
console.error(‘Validation failed:’, validationResult.error.details);
} else {
console.log(‘Validation succeeded:’, validationResult.value);
}

In this example, we have a userData object that we want to validate. The validate method checks if the data conforms to the schema and returns the validation result. If the validation fails, it provides detailed error messages; otherwise, it confirms the data is valid.

Advanced Validation Techniques

Valkey supports more advanced validation techniques, including custom validation rules, conditional validations, and nested objects. Here are some examples:

Custom Validation Rules

You can define custom validation rules using Valkey’s custom method:

javascript
const phoneNumberSchema = valkey.string().custom((value, helpers) => {
const phoneRegex = /^[0-9]{10}$/;
if (!phoneRegex.test(value)) {
return helpers.error('Invalid phone number');
}
return value;
});
const userSchema = valkey.object({
name: valkey.string().required(),
phone: phoneNumberSchema.required(),
});const userData = {
name: ‘Jane Doe’,
phone: ‘1234567890’,
};const validationResult = userSchema.validate(userData);if (validationResult.error) {
console.error(‘Validation failed:’, validationResult.error.details);
} else {
console.log(‘Validation succeeded:’, validationResult.value);
}

In this example, we define a custom validation rule for a phone number, ensuring it consists of exactly 10 digits.

Conditional Validations

Valkey also allows conditional validations based on the values of other fields:

javascript
const userSchema = valkey.object({
name: valkey.string().required(),
age: valkey.number().integer().positive().required(),
drivingLicense: valkey.string().when('age', {
is: val => val >= 18,
then: valkey.string().required(),
otherwise: valkey.string().optional(),
}),
});
const userData = {
name: ‘John Doe’,
age: 17,
};const validationResult = userSchema.validate(userData);if (validationResult.error) {
console.error(‘Validation failed:’, validationResult.error.details);
} else {
console.log(‘Validation succeeded:’, validationResult.value);
}

In this example, the drivingLicense field is required only if the age field is 18 or older.

Nested Objects

Valkey can handle nested objects, enabling validation of complex data structures:

javascript
const addressSchema = valkey.object({
street: valkey.string().required(),
city: valkey.string().required(),
zipCode: valkey.string().length(5).required(),
});
const userSchema = valkey.object({
name: valkey.string().required(),
email: valkey.string().email().required(),
age: valkey.number().integer().positive().required(),
address: addressSchema.required(),
});const userData = {
name: ‘John Doe’,
email: ‘john.doe@example.com’,
age: 30,
address: {
street: ‘123 Main St’,
city: ‘Anytown’,
zipCode: ‘12345’,
},
};const validationResult = userSchema.validate(userData);if (validationResult.error) {
console.error(‘Validation failed:’, validationResult.error.details);
} else {
console.log(‘Validation succeeded:’, validationResult.value);
}

Here, we define an addressSchema for the address field within the userSchema. This allows us to validate nested objects effectively.

Transformations

In addition to validation, Valkey supports data transformations. You can transform data during validation using the transform method:

javascript
const userSchema = valkey.object({
name: valkey.string().trim().required(),
email: valkey.string().email().lowercase().required(),
age: valkey.number().integer().positive().required(),
});
const userData = {
name: ‘ John Doe ‘,
email: ‘JOHN.DOE@EXAMPLE.COM’,
age: 30,
};const validationResult = userSchema.validate(userData);if (validationResult.error) {
console.error(‘Validation failed:’, validationResult.error.details);
} else {
console.log(‘Transformed Data:’, validationResult.value);
}

In this example, the name field is trimmed, and the email field is converted to lowercase during validation.

Error Handling

Valkey provides detailed error messages when validation fails. You can customize these error messages to suit your needs:

javascript
const userSchema = valkey.object({
name: valkey.string().required().messages({
'string.empty': 'Name cannot be empty',
'any.required': 'Name is required',
}),
email: valkey.string().email().required().messages({
'string.email': 'Invalid email format',
'any.required': 'Email is required',
}),
});
const userData = {
name: ,
email: ‘invalid-email’,
};const validationResult = userSchema.validate(userData);if (validationResult.error) {
validationResult.error.details.forEach(err => {
console.error(err.message);
});
} else {
console.log(‘Validation succeeded:’, validationResult.value);
}

In this example, custom error messages are defined for the name and email fields, providing more user-friendly feedback.

Integration with Express.js

Valkey can be seamlessly integrated with Express.js for validating request data in web applications:

javascript
const express = require('express');
const { valkey } = require('valkey');
const app = express();
app.use(express.json());const userSchema = valkey.object({
name: valkey.string().required(),
email: valkey.string().email().required(),
age: valkey.number().integer().positive().required(),
});app.post(‘/users’, (req, res) => {
const validationResult = userSchema.validate(req.body);if (validationResult.error) {
return res.status(400).json({ errors: validationResult.error.details });
}

res.status(201).json({ message: ‘User created successfully’, user: validationResult.value });
});

app.listen(3000, () => {
console.log(‘Server is running on port 3000’);
});

In this example, we validate the incoming request data for creating a new user. If validation fails, a 400 Bad Request response is sent with detailed error messages.

Conclusion

Valkey is a powerful and flexible library for data validation and transformation in JavaScript. Its comprehensive set of features allows developers to define complex validation schemas, apply custom rules, handle nested objects, and perform data transformations effortlessly. With detailed error handling and seamless integration with web frameworks like Express.js, Valkey ensures data integrity and consistency in applications, reducing the likelihood of bugs and errors.

Getting started with Valkey is straightforward, and its intuitive API makes it easy to define and validate schemas. Whether you’re building simple web forms or complex applications, Valkey provides the tools you need to validate and transform data effectively.

By following the examples and techniques demonstrated in this article, you can leverage Valkey to enhance the robustness and reliability of your JavaScript applications. As you continue to explore and utilize Valkey, you’ll discover even more capabilities and ways to simplify your data validation processes.