When calling instance .validate() it returns me a sequelize object instead of ValidationError object.
Is that supposed to happen ?
Hey @bschveitzer. Can you post a code example and your sequelize version please? Thank you :)
Hi @RobinBuschmann,
as I see this issue has gone silent, and I'm experiencing the same issue, I'll post the code here:
let user = new User(data);
let errors = await user.validate();
console.log(errors);
this will output an instance of the user that I just created, no validation errors.
I'm using VSCode and the intellisense shows the following:
There is in fact an error in the data I'm supplying, as it is thrown when I'm trying to save the model, but something here seems to go wrong.
To elaborate on the issue: I found that this problem occurs whenever you supply a validator function that returns either true or false
With the following code:
// within my model definition
@Unique
@IsEmail
@Is("emailAvailable", emailAvailable)
@Column
email: string;
works with the following validator:
const emailAvailable = async function (email: string): Promise<void> {
const user = await User.findOne({ where: { email } });
if (user != null && user.id !== this.id) {
throw new Error("Email already in use");
}
};
fails with the following validator:
const emailAvailable = async function (email: string): Promise<boolean> {
const user = await User.findOne({ where: { email } });
return user == null || user.id === this.id;
};
I'm not sure if this is intended behavior, as custom validators for Sequelize seem to be badly documented, but at least I found the source for my issues.
Ah ok, I got it. Validation works differently for the two latest sequelize major versions. While validate() in version 3 resolves with an error if one exists, it rejects the promise in version 4:
user.validate().then(err => ...) // 3.X
user.validate().catch(err => ...) // 4.X
sequelize-typescript currently supports both major versions. So the actual issue is in the sequelize-typescript typings. It should be something like
validate(...): Promise<ValidationError /*v3*/ | Model> than the current type definition.
Is fixed with [email protected]
Most helpful comment
Ah ok, I got it. Validation works differently for the two latest sequelize major versions. While
validate()in version 3 resolves with an error if one exists, it rejects the promise in version 4:sequelize-typescript currently supports both major versions. So the actual issue is in the sequelize-typescript typings. It should be something like
validate(...): Promise<ValidationError /*v3*/ | Model>than the current type definition.