Tools
Tools: Day 35 of #100DaysOfCode — Data Validation
2026-03-09
0 views
admin
Why Data Validation Is Important ## Example of a Bad Request ## Mongoose Schema Validation ## Example Schema ## Common Mongoose Validation Rules ## Custom Validation in Mongoose ## Example ## Handling Validation Errors ## Example Pattern ## Common HTTP Status Codes for Validation ## Request Validation Before the Database (Express Level) ## Example ## Popular Validation Libraries for Node.js ## What Is Sanitization? ## Example: Lowercase Email ## Example: Trim Whitespace ## Key Takeaways ## Final Thoughts When building APIs, data validation is one of the most important parts of backend development. If you don't validate incoming data, your database and application logic can easily break. Day 35 was all about understanding what data validation is, why it matters, and how to implement it in Node.js using Mongoose and Express. Data validation ensures that the data sent by users or clients is correct, safe, and usable before it reaches your database. Without validation, your application may store: A properly designed API should reject this request instead of saving it. When using MongoDB with Mongoose, you can define validation rules directly inside your schema. This ensures that invalid data never reaches the database. Some important schema validation options to know: ⚠️ Important note:
unique is not technically a validator — it creates a unique index in MongoDB that prevents duplicate values. Sometimes built-in validation rules are not enough. In those cases, you can create custom validation functions. In real projects, developers usually use regex patterns or validation libraries for things like emails and passwords. When validation fails, Mongoose throws a ValidationError. You should catch this error and return a proper HTTP response. Both are used in APIs, but 422 is commonly used specifically for validation errors. Sometimes validation should happen before Mongoose is even called. This prevents unnecessary database operations. This is known as request-level validation. Things you typically check: If validation fails, you reject the request early. In larger applications, developers usually rely on dedicated validation libraries. These libraries help keep validation clean, reusable, and centralized. Common validation libraries include: Benefits of using validation libraries: Validation checks whether data is valid. Sanitization cleans the data before storing it. Examples of sanitization include: Sanitization helps maintain consistent and clean data inside your database. Here are the main things that you need to know about data validation in Node.js APIs: Data validation is one of those backend concepts that seems simple but becomes critical as applications grow. Without it, even a small API can quickly become unstable. As I continue my #100DaysOfCode journey, I'm starting to see how validation, error handling, and clean data structures form the foundation of reliable backend systems. If you're also learning backend development, I'd love to hear: How do you handle validation in your APIs? Thanks for reading. Feel free to share your thoughts! Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well For further actions, you may consider blocking this person and/or reporting abuse CODE_BLOCK:
{ "title": "", "age": "abc"
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
{ "title": "", "age": "abc"
} CODE_BLOCK:
{ "title": "", "age": "abc"
} CODE_BLOCK:
const userSchema = new mongoose.Schema({ name: { type: String, required: true, minlength: 3 }, age: { type: Number, min: 0 }, email: { type: String, required: true, unique: true }
}); Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
const userSchema = new mongoose.Schema({ name: { type: String, required: true, minlength: 3 }, age: { type: Number, min: 0 }, email: { type: String, required: true, unique: true }
}); CODE_BLOCK:
const userSchema = new mongoose.Schema({ name: { type: String, required: true, minlength: 3 }, age: { type: Number, min: 0 }, email: { type: String, required: true, unique: true }
}); CODE_BLOCK:
email: { type: String, validate: { validator: function(v) { return v.includes("@"); }, message: "Invalid email" }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
email: { type: String, validate: { validator: function(v) { return v.includes("@"); }, message: "Invalid email" }
} CODE_BLOCK:
email: { type: String, validate: { validator: function(v) { return v.includes("@"); }, message: "Invalid email" }
} CODE_BLOCK:
try { const user = await User.create(req.body); res.status(201).json(user);
} catch (error) { res.status(400).json({ message: error.message });
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
try { const user = await User.create(req.body); res.status(201).json(user);
} catch (error) { res.status(400).json({ message: error.message });
} CODE_BLOCK:
try { const user = await User.create(req.body); res.status(201).json(user);
} catch (error) { res.status(400).json({ message: error.message });
} CODE_BLOCK:
if (!req.body.title) { return res.status(400).json({ message: "Title is required" });
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
if (!req.body.title) { return res.status(400).json({ message: "Title is required" });
} CODE_BLOCK:
if (!req.body.title) { return res.status(400).json({ message: "Title is required" });
} CODE_BLOCK:
email: { type: String, lowercase: true
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
email: { type: String, lowercase: true
} CODE_BLOCK:
email: { type: String, lowercase: true
} CODE_BLOCK:
name: { type: String, trim: true
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
name: { type: String, trim: true
} CODE_BLOCK:
name: { type: String, trim: true
} - Empty values in the database
- Wrong data types
- Invalid emails
- Unexpected values
- Data that breaks your UI or backend logic
- Potentially malicious input - title is empty
- age should be a number but is a string - Define custom validation logic
- Return custom error messages - Required request fields
- Correct data types
- Valid formats
- Business rules - express-validator - Cleaner API controllers
- Reusable validation schemas
- Better error messages
- More advanced validation rules - Removing extra spaces
- Converting text to lowercase
- Normalizing formats - Always validate user input
- Use Mongoose schema validation to protect your database
- Implement custom validators when built-in rules aren't enough
- Handle validation errors properly in your API
- Validate requests before hitting the database
- Use libraries like Joi or Zod for scalable validation
- Sanitize input to keep data clean
how-totutorialguidedev.toainodedatabase