【问题标题】:How to do validate image dimensions through angular forms or Is it possible validate to using angular forms?如何通过角度形式验证图像尺寸或是否可以验证使用角度形式?
【发布时间】:2021-08-17 07:16:59
【问题描述】:

我使用了角度形式和文件输入类型以及自定义验证器。

问题是,

每当表单值发生变化时,我只会得到假路径 URL。假路径 URL 没有文件元数据。那么我如何验证图像尺寸。

fake_path : C:\fakepath\lutosa_images_480x600.jpeg .

可以使用角形吗?

是否可以从 fake_path 获取文件元数据?

html 文件:

<form [formGroup]="productCategoryAddForm">
<input
type="file"
accept="image/*"
(change)="getImageData($event)"
formControlName="product_category_image"
/>
</form>

ts 文件:

initializeForm() {
this.productCategoryAddForm = this.fb.group({
product_category_image: [null, [Validators.required, dimensionValidator]],
});
}

自定义验证器

import { AbstractControl } from '@angular/forms';

export interface ReturnType {
[key: string]: boolean;
}

export function dimensionValidator(control: AbstractControl): ReturnType | null {
console.log('control.value', control.value);

if (control.value) {
//success 
} else {
//fail
}
}

注意:

没有角度形式,我可以验证图像尺寸。使用 change()FileReader();

【问题讨论】:

  • 您可以使用 fileReader() 添加代码以检查 dimensionValidator 内的图像尺寸。
  • @GaurangDhorda 我得到了这个值 fake_path : C:\fakepath\lutosa_images_480x600.jpeg 所以我不能使用 fileReader() 直接获取图像尺寸 dimensionValidator。

标签: angular angular-reactive-forms reactive-forms


【解决方案1】:

是的,可以验证。您可以使用 patchValue() 并将图像属性发送到 customvalidator。

getImageData() 中的补丁值:

 getImageData(data: any) {
 if (data.target.files[0]) {
    const file = data.target.files[0];
    const reader: any = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e: any) => {
      this.base64Data = reader.result.split(',').pop();
      const image = new Image();
      image.src = e.target.result;
      image.onload = (rs) => {
        const width = rs.currentTarget['width'];
        const height = rs.currentTarget['height'];
        const dimensions = {
          width,
          height,
        };
        this.productCategoryAddForm.patchValue({ product_category_image: dimensions });
      };
    };
  }
}

自定义验证器:

import { AbstractControl } from '@angular/forms'; 

export interface ReturnType {
   [key: string]: boolean; 
 }

 export function dimensionValidator(control: AbstractControl): 
 ReturnType| null 
 {
   if (typeof control.value === 'object') {
    if (control.value) {
      const width = control.value.width;
      const height = control.value.height;
      const invalidDimension = width !== 600 && height !== 300;
      return invalidDimension ? { invalidDimensionError: true } : null;
     }
    } else {
     return null;
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多