Build with Confidence: 15 Essential Node.js Data Validations to Secure Your Tech Product
Mohit Sehgal
Building custom eCommerce Solutions | Full Stack Developer - Node.js PostgreSQL
Data validation is crucial for maintaining the integrity and security of web applications. It helps to:
There are many popular libraries in Node.js like Joi, Validator.js, and Express- Validator for validating the data. But in this post, we will explore how you can implement the same validations without using any library.
Email Validation
It makes sure that the input is in a valid email format, preventing malformed or invalid emails.
const isValidEmail = (email) => {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
};
Using Joi.
const Joi = require('joi');
const schema = Joi.string().email();
const result = schema.validate('[email protected]');
Number validation
const isNumber = (value) => !isNaN(value);
String Validation
const isValidLength = (str, min, max) => str.length >= min && str.length <= max;
Phone Number Validation
const isValidPhoneNumber = (phone) => /^\d{10}$/.test(phone);
Password strength validation
const isStrongPassword = (password) => {
const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;
return re.test(password);
};
Date Validation
const isValidDate = (date) => !isNaN(Date.parse(date));
UUID Validation
const isUUID = (uuid) => /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(uuid);
URL Validation
const isValidURL = (url) => {
try {
new URL(url);
return true;
} catch (_) {
return false;
}
};
领英推荐
Alphanumeric Validation
const isAlphanumeric = (str) => /^[a-z0-9]+$/i.test(str);
IP Address Validation
const isValidIP = (ip) => /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(\d{1,3}\.){2}\d{1,3}$/.test(ip);
Credit Card Validation
const isValidCreditCard = (cc) => /^[0-9]{16}$/.test(cc);
Hex Color Code Validation
const isHexColor = (color) => /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i.test(color);
JSON Validation
const isValidJSON = (str) => {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
};
Domain Name Validation
const isValidDomain = (domain) => {
const re = /^(?!:\/\/)([a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+)$/;
return re.test(domain);
};
File Upload Validation
Example- If you want to validate image to be PNG/JPG format. Also size to be maximum 5 MB. We can use Joi.
const schema = Joi.object({
file: Joi.object({
mimetype: Joi.string().valid('image/jpeg', 'image/png').required(),
size: Joi.number().max(5000000).required() // Max 5MB
})
});
schema.validate(uploadedFileObject);
Best Practices for Data Validation
Conclusion
Data validation in Node.js is essential for maintaining application security, data integrity, and enhancing user experience.
By leveraging built-in methods and popular libraries like Joi, Validator.js, and Express-Validator, you can implement robust validation mechanisms.
Following best practices ensures your application remains secure and efficient while providing a smooth user experience.