I am trying to add a custom validator on a column. This custom validator checks the value of the other field in Model and the value of the column and then decides the action that has to be taken.
But the issue is I am getting an error at if(this.employee.....:
The containing arrow function captures the global value of 'this' which implicitly has type 'any'.
@Column({
type: DataType.BIGINT, `
validate:{
custVal:(value:number)=>{
if(this.employee===null && value===null){
throw new Error("Enter valid value");
}
}
}
})
employeeId: number;
@BelongsTo(() => Employees, "employeeId")
public employee: Employees;
I also tried using @Is decorator but got the same error.
@Is("custVal",(value:number)=>{
if(this.employee===null && value===null){
throw new Error("Enter valid value");
}
})
@Column({
type: DataType.BIGINT, `
})
employeeId: number;
@BelongsTo(() => Employees, "employeeId")
public employee: Employees;
@pratikshah14 For model wide validation see this: http://docs.sequelizejs.com/manual/models-definition.html#model-wide-validations
@RobinBuschmann thank you for the reply. I have checked it out. But @Column decorator has a property validate which takes a function, here is the defintion:
typescript
/**
* custom validations are also possible
*
* Implementation notes :
*
* We can't enforce any other method to be a function, so :
*
*typescript
* [name: string] : ( value : any ) => boolean;
* ``
*
* doesn't work in combination with the properties above
*
* @see https://github.com/Microsoft/TypeScript/issues/1889
*/
[name: string]: any;
````
I wanted to use that & even @Is says that we can define our own function, but problem is that thethisoperator inside the function is of typeany& hence I am not able to usethis.employee`.
Hey @pratikshah14 sry for the late reply. Yes that's the intended behaviour. @Is is only for column validation, so there shouldn't be a way to access the whole model instance within those validators. Thats why you should use model wide validation like so:
@Table({
validate: {
myCustomValidator(this: YouModel) {
// your validation goes here
}
}
})
Closing this due to inactivity
Sorry for the late reply, thank you this is working.
that snippet would do well in the docs -- this issue took a minute to find as a reference on model wide validation
Most helpful comment
Hey @pratikshah14 sry for the late reply. Yes that's the intended behaviour.
@Isis only for column validation, so there shouldn't be a way to access the whole model instance within those validators. Thats why you should use model wide validation like so: