Create data validation before database operations
✓Works with OpenClaudeYou are a backend developer building database safety. The user wants to create a validation layer that checks data integrity before any database operation.
What to check first
- Verify your database driver is installed:
npm list(check forpg,mysql2,mongodb, etc.) - Check if you have a validation library available:
npm list joiornpm list zod - Identify your database schema structure and required fields
Steps
- Install a validation library:
npm install joi(or use built-in Node.js validation) - Define a schema object that matches your database table structure with field types and constraints
- Create a validation function that accepts raw user input before it reaches your database
- Call
.validate()on the schema with the incoming data object - Check the validation result for errors using
.errorproperty - Return early with validation error details if validation fails
- Only proceed with the database INSERT/UPDATE operation if validation passes
- Log validation failures for debugging and security auditing
Code
const Joi = require('joi');
// Define your validation schema
const userSchema = Joi.object({
email: Joi.string()
.email()
.required()
.messages({ 'string.email': 'Must be a valid email' }),
password: Joi.string()
.min(8)
.required()
.pattern(/[A-Z]/)
.messages({ 'string.pattern.base': 'Password must contain uppercase' }),
age: Joi.number()
.integer()
.min(18)
.max(120)
.optional(),
name: Joi.string()
.trim()
.required()
.max(100),
phone: Joi.string()
.pattern(/^\d{10}$/)
.optional()
.messages({ 'string.pattern.base': 'Phone must be 10 digits' })
});
// Create validation middleware/function
async function validateAndSaveUser(userData, db) {
// Validate against schema
const { error, value } = userSchema.validate(userData, {
abortEarly: false,
stripUnknown: true
});
if (error) {
const validationErrors = error.details.map(detail => ({
field: detail.path[0],
message: detail.message
}));
return {
success: false,
errors: validationErrors
};
}
try {
// Only reach database if validation passed
const result = await db.query(
'INSERT INTO users (email, password, age, name, phone) VALUES ($1, $2, $3, $4, $5) RETURNING id',
[value.email, value.password, value.age, value.name, value.phone]
);
return {
success:
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Database Skills
Other Claude Code skills in the same category — free to download.
Migration Generator
Generate database migration files
Query Optimizer
Analyze and optimize slow database queries
Schema Designer
Design database schema from requirements
Seed Data Generator
Generate database seed/sample data
Index Advisor
Suggest database indexes based on query patterns
ORM Model Generator
Generate ORM models from database schema
SQL to ORM
Convert raw SQL queries to ORM syntax
Database Backup Script
Create database backup and restore scripts
Want a Database skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.