I am trying to write a custom validator to check if a given URL content type is pdf, doc or docx. If the url is not one of these, the user should not be able to save.
In my component I have:
checkUrl(): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
const validFiles = [
'application/msword',
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
]
const url = control.value.toLowerCase()
const xhttp = new XMLHttpRequest()
xhttp.open('HEAD', url)
xhttp.onreadystatechange = function() {
if (this.readyState == this.DONE) {
console.log(this.status)
if (!validFiles.includes(this.getResponseHeader('Content-Type')!)) {
console.log('Match')
return { notValid: { value: control.value } }
}
}
}
xhttp.send()
return null
}
I also have
url: [
'',
[
Validators.required,
Validators.pattern(
'(http://www.|https://www.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$'
),
this.checkUrl(),
],
],
And
formControlName="url" type="url" pattern="(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$"
in the HTML.
Now when I enter the 77677 into the URL, I do get the error of not a url. However, if I enter https://www.google.com, it is accepted which it should not be as that is not a pdf, doc or docx file. Only if the user enters a url which is a pdf, doc or docx which I am checking by content-type should they be allowed to save.
As far as I can tell this should be working, but it is not and I cannot see what I am doing wrong.