Skip to content

Commit

Permalink
➕ isDataURI
Browse files Browse the repository at this point in the history
  • Loading branch information
Bunlong committed Sep 30, 2020
1 parent 9b56617 commit a711071
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Validate is a standard Deno module for validating string.
* [x] isByteLength
* [x] isCreditCard
* [x] isCurrency
* [ ] isDataURI
* [x] isDataURI
* [ ] isDate
* [ ] isDecimal
* [ ] isDivisibleBy
Expand Down
40 changes: 40 additions & 0 deletions src/libs/isDataURI.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// @ts-ignore allowing typedoc to build
import assertString from '../utils/assertString.ts';

const validMediaType = /^[a-z]+\/[a-z0-9\-\+]+$/i;
const validAttribute = /^[a-z\-]+=[a-z0-9\-]+$/i;
const validData = /^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i;

export const isDataURI = (str: string) => {
assertString(str);
let data = str.split(',');
if (data.length < 2) {
return false;
}
const attributes = (data.shift() as string).trim().split(';');
const schemeAndMediaType = attributes.shift() as string;
if (schemeAndMediaType.substr(0, 5) !== 'data:') {
return false;
}
const mediaType = schemeAndMediaType.substr(5);
if (mediaType !== '' && !validMediaType.test(mediaType)) {
return false;
}
for (let i = 0; i < attributes.length; i++) {
if (
i === attributes.length - 1 &&
attributes[i].toLowerCase() === 'base64'
) {
// ok
} else if (!validAttribute.test(attributes[i])) {
return false;
}
}
for (let i = 0; i < data.length; i++) {
if (!validData.test(data[i])) {
return false;
}
}

return true;
};
2 changes: 2 additions & 0 deletions src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ export * from './libs/isByteLength.ts';
export * from './libs/isCreditCard.ts';
// @ts-ignore allowing typedoc to build
export * from './libs/isCurrency.ts';
// @ts-ignore allowing typedoc to build
export * from './libs/isDataURI.ts';

0 comments on commit a711071

Please sign in to comment.