mirror of
https://github.com/sasjs/adapter.git
synced 2025-12-11 01:14:36 +00:00
Merge pull request #326 from sasjs/isUrl-fix
This commit is contained in:
39
src/test/utils/isUrl.spec.ts
Normal file
39
src/test/utils/isUrl.spec.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { isUrl } from '../../utils/isUrl'
|
||||
|
||||
describe('urlValidator', () => {
|
||||
it('should return true with an HTTP URL', () => {
|
||||
const url = 'http://google.com'
|
||||
|
||||
expect(isUrl(url)).toEqual(true)
|
||||
})
|
||||
|
||||
it('should return true with an HTTPS URL', () => {
|
||||
const url = 'https://google.com'
|
||||
|
||||
expect(isUrl(url)).toEqual(true)
|
||||
})
|
||||
|
||||
it('should return true when the URL is blank', () => {
|
||||
const url = ''
|
||||
|
||||
expect(isUrl(url)).toEqual(false)
|
||||
})
|
||||
|
||||
it('should return false when the URL has not supported protocol', () => {
|
||||
const url = 'htpps://google.com'
|
||||
|
||||
expect(isUrl(url)).toEqual(false)
|
||||
})
|
||||
|
||||
it('should return false when the URL is null', () => {
|
||||
const url = null
|
||||
|
||||
expect(isUrl((url as unknown) as string)).toEqual(false)
|
||||
})
|
||||
|
||||
it('should return false when the URL is undefined', () => {
|
||||
const url = undefined
|
||||
|
||||
expect(isUrl((url as unknown) as string)).toEqual(false)
|
||||
})
|
||||
})
|
||||
@@ -1,16 +1,17 @@
|
||||
/**
|
||||
* Checks if string is in URL format.
|
||||
* @param url - string to check.
|
||||
* @param str - string to check.
|
||||
*/
|
||||
export const isUrl = (url: string): boolean => {
|
||||
const pattern = new RegExp(
|
||||
'^(http://|https://)[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$',
|
||||
'gi'
|
||||
)
|
||||
export const isUrl = (str: string): boolean => {
|
||||
const supportedProtocols = ['http:', 'https:']
|
||||
|
||||
if (pattern.test(url)) return true
|
||||
else
|
||||
throw new Error(
|
||||
`'${url}' is not a valid url. An example of a valid url is 'http://valid-url.com'.`
|
||||
)
|
||||
try {
|
||||
const url = new URL(str)
|
||||
|
||||
if (!supportedProtocols.includes(url.protocol)) return false
|
||||
} catch (_) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user