输入type =“ file”的角反应形式自定义验证器检查照片尺寸

问题描述

我试图验证上传的照片是否为方形格式,所以我创建了一个自定义异步验证器,该验证器将在控制台中返回正确的值,如以下代码所示。似乎失败的原因是表单没有收到此状态,因此无法正确更新自身。

这是创建表单的相关部分:

    this.form = this.formBuilder.group({
                name: [this.user.name,[Validators.required,Validators.minLength(2),Validators.maxLength(100)]],username: [this.user.username,Validators.minLength(3),Validators.maxLength(20),Validators.pattern('^[A-Za-z0-9]+$')]],phone: [this.user.phone,[Validators.minLength(9),Validators.maxLength(9)]],email: [this.user.email,Validators.email]],photo: [null,[Validators.nullValidator],[photovalidator]]
});

这是自定义验证程序打字稿文件

export function photovalidator(control: AbstractControl): Observable<ValidationErrors | null> {
    const value = control.value;
    if (isArray(value) && value.length > 0) {
        return loadImageData(control).pipe(tap(res => { console.log(res) }));
    } else {
        return of(null);
    }
}

function loadImageData(control: AbstractControl): Observable<ValidationErrors | null> {
const image: HTMLImageElement = new Image();
     return new Observable(observer => {
         image.onload = _ => {
             if (image.naturalHeight !== image.naturalWidth) {
                 observer.next({
                     photo: true
                 });
             } else {
                 observer.next(null);
             }
         };
 
         image.src = 'data:image/png;base64,' + control.value[0].content;
     });
}

上载正方形图像或上载非正方形图像时,控制台的输出正确。我在这里想念什么吗?它显示为表单返回时未从第一个函数接收值。

输出

{photo: true} -> when photo isn't square
null          -> when photo is square
null          -> when photo is square

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)