[英]Set Custom Validation for File Upload in angular Form is not working as expected
I want to implement upload pdf file validation.我想实现上传 pdf 文件验证。 If uploaded pdf file is password protected then it should not be allowed.如果上传的 pdf 文件受密码保护,则不应允许。 I am using angular typescript.我正在使用 angular typescript。
Below is My Custom Validation Function以下是我的自定义验证 Function
export function pdfFileValidator(file: File,fileExtension:string): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
var res = false;
if(fileExtension.toLowerCase() === 'pdf'){
pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js'
var url = URL.createObjectURL(file);
const loadingTask = pdfjsLib.getDocument(url);
loadingTask.promise.then(function(pdf) {console.error(pdf)})
.catch((e:PasswordException) => {
console.error("File is Password Protected")
res = true;
}).finally( () =>{
return {
'EncryptedFileViolated': res,
};
});
}
console.error("response =",res)
return null;
};
}
Below is my set Validation function下面是我设置的验证 function
setFileValidators(fileSize: number, fileExtension: string,file:File) {
this.form.get('file')?.setValidators([FileSizeValidator(fileSize, this.maxSizeAllowedInMB),
FileExtensionValidator(fileExtension, ['pdf','jpg','png']),pdfFileValidator(file,fileExtension)]);
this.form.get('file')!.updateValueAndValidity()
console.error(this.form);
}
How It is working now它现在是如何工作的
these two lines executed earlier without waiting for the complete execution of the pdfFileValidator
function这两行早先执行,无需等待pdfFileValidator
function 的完整执行
this.form.get('file')!.updateValueAndValidity()
console.error(this.form);
And Form shows status = valid
并且表格显示status = valid
I want this.form.get('file')?.setValidators()
should wait for completion of pdfFileValidator()
function and after that execute updateValueAndValidity()
function.我希望this.form.get('file')?.setValidators()
应该等待pdfFileValidator()
function 完成,然后执行updateValueAndValidity()
function。
How we can implement this?我们如何实现这一点?
You pdfJs library function is taking time and you have set synchronous validation with setValidators
function and due to this its not working as you want.您的 pdfJs 库 function 需要时间,并且您已使用setValidators
function 设置同步验证,因此它无法按您的意愿工作。
You have to set asynchronous validators withsetasyncvalidators您必须使用setasyncvalidators设置异步验证器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.