Best practices for Data Validation in Node.js MVC Architecture #4805
|
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 |
Answered by
opjarretop
Dec 12, 2023
Replies: 0 comments 1 reply
|
@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. |
0 replies
Answer selected by
marco-ippolito
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to 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.