File size: 1,039 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
export const checkValidChars = ( value: string ) => {
const validChars = /^([\u0E00-\u0E7Fa-z0-9-._*]+)$/g;
return validChars.test( value );
};
export default function validateDomain( value: string ) {
try {
if ( value ) {
// Only allow domains with a dot in them (not localhost, for example).
if ( ! value.includes( '.' ) ) {
throw new Error( 'Invalid domain' );
}
let normalised = value;
// If the domain doesn't start with http:// or https://, add https://
if ( ! normalised.startsWith( 'http://' ) && ! normalised.startsWith( 'https://' ) ) {
normalised = 'https://' + normalised;
}
// Test if we can parse the URL. If we can't, it's invalid.
const url = new URL( normalised );
// Check if the protocol is 'http' or 'https'.
const protocolCheck = url.protocol === 'http:' || url.protocol === 'https:';
if ( ! protocolCheck ) {
return false;
}
const { hostname } = url;
return checkValidChars( hostname );
}
return undefined;
} catch ( e ) {
return false;
}
}
|