Best practices for Data Validation in Node.js MVC Architecture #50879
-
Hello, I'm seeking guidance on best practices for data validation in Node.js, especially in the context of an MVC architecture. My main questions are:
async validateImport(isUpdate: boolean): Promise<{ isValid: boolean, message?: string }> {
if (this.userId && typeof (this.userId) != 'number' || Number.isNaN(this.userId)) {
return { isValid: false, message: "invalid userId, must be a number" };
}
if (!this.employeeId) {
return { isValid: false, message: "missing employee ID" };
}
if (!this.validateEmployeeId(this.employeeId)) {
return { isValid: false, message: "employee ID invalid format" };
}
if (typeof (this.email) != 'string') {
return { isValid: false, message: "email not a string" };
}
if (!this.email) {
return { isValid: false, message: "missing email" };
}
return { isValid: true };
} This approach works, but I'm wondering if it's less advisable compared to using a schema, which might be more readable and maintainable. Are there scenarios where custom validation like this is more suitable, especially when dealing with complex or highly specific validation requirements?
Discussion, experiences and thoughts would be greatly appreciated! Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
@WUKLH I've found using a library like Joi or Zod tends to scale a lot easier. There is nothing stopping you from creating custom validation when needed. Custom validation is a valid option and it really depends on your use case. |
Beta Was this translation helpful? Give feedback.
@WUKLH I've found using a library like Joi or Zod tends to scale a lot easier. There is nothing stopping you from creating custom validation when needed. Custom validation is a valid option and it really depends on your use case.