Javascript 无法在具有类验证器的父类的构造函数中使用validate
我想在对象构造函数中使用validateSync,但无法将其与继承一起使用 我有这样的想法:Javascript 无法在具有类验证器的父类的构造函数中使用validate,javascript,node.js,typescript,class-validator,Javascript,Node.js,Typescript,Class Validator,我想在对象构造函数中使用validateSync,但无法将其与继承一起使用 我有这样的想法: import { IsNotEmpty, IsString, validateSync, validate } from 'class-validator'; class Animal { @IsNotEmpty() @IsString() public name: string; constructor(name: string) { this.n
import { IsNotEmpty, IsString, validateSync, validate } from 'class-validator';
class Animal {
@IsNotEmpty()
@IsString()
public name: string;
constructor(name: string) {
this.name = name;
this.validate() // this method calls validate of class Dog, since this is an instance of Dog
}
protected validate() {
const errors = validateSync(this);
if (errors.length > 0) {
console.log("Animal validation error: ", errors)
}
}
}
class Dog extends Animal {
@IsNotEmpty()
@IsString()
public breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed
this.validate()
}
protected validate() {
const errors = validateSync(this);
if (errors.length > 0) {
console.log("Dog validation error: ", errors)
}
}
}
const dog = new Dog('Aaron', 'Golden Retriever')
结果是:
Dog validation error: [ ValidationError {
target: Dog { name: 'Aaron' },
value: undefined,
property: 'breed',
children: [],
constraints:
{ isString: 'breed must be a string',
isNotEmpty: 'breed should not be empty' } } ]
当我调用Dog构造函数时,代码会运行super(),然后运行Animal类的这个.validate()。此方法验证Dog的一个实例,因为Animal没有“繁殖”属性,所以代码抛出上述错误
我不知道如何解决这个问题,也许将验证放在构造函数中不是一个好主意
有解决方法或更好的方法吗?出现错误的原因不是因为
Animal
没有breed
属性(事实上是这样的,因为实例实际上是Dog
),而是因为在设置所有要验证的值之前调用了验证(其中一个)。另一件事是,你做了两次验证,这听起来不对
class Dog extends Animal {
constructor(name: string, breed: string) {
super(name); // <-- validation gets called in the parent but you did't set the breed property yet
this.breed = breed;
this.validate(); // <-- validation gets called for the second time, but this time it passes
}
}
另一个注意事项是,您似乎不需要在父类和子类中声明相同的确切方法
validate()
。是的,这正是我所想的。我唯一想做的就是避免在构造函数之外检查属性。另外,由于Animal类可以实例化(因为它不是抽象类),所以我不能在构造函数内调用validate()(出于您指出的原因),因此只为子类调用validate不是一个好主意。正如您所说,唯一合理的解决方案是在创建实例后调用验证。谢谢:)
const dog = new Dog('Aaron');
// do some stuff like determine the breed...
dog.breed = 'Golden Retriever';
// do some more stuff
const validationResult = dog.validate(); // did I succeed?