Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stoyan-scava/d18c6b5c827e0d43942de8ca57b37993 to your computer and use it in GitHub Desktop.
Save stoyan-scava/d18c6b5c827e0d43942de8ca57b37993 to your computer and use it in GitHub Desktop.
Validator for file extensions
/**
* Validator of file extensions
*/
export class ExtensionValidator {
private readonly detector = new ExtensionDetector();
constructor() {
}
/**
* E.g. 'txt' from 'example.txt'
* @param filename
* @param extension extension text without a dot
* @param case_sensitive default:false
*/
hasExtension(filename: string, extension: string, case_sensitive?: boolean): boolean {
const fileExtension = this.detector.getExtension(filename).substring(1); // removing the dot
if (case_sensitive) {
return fileExtension === extension
} else {
return filename.toLowerCase() === extension.toLowerCase();
}
}
/**
* @return void on match. e.g. 'txt' from 'example.txt'
* @throws Invalid extension
*/
check(filename: string, extension: string, case_sensitive?: boolean): void {
const fileExtension = this.detector.getExtension(filename);
if (case_sensitive) {
if (fileExtension === extension) return;
} else {
if (filename.toLowerCase() === extension.toLowerCase()) return;
}
throw new Error("Invalid extension");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment