sp/src/utils/domainUtils.js

72 lines
2.2 KiB
JavaScript

/**
* Clean domain input by removing http://, https://, www., and trailing slashes
* @param {string} input - The domain input string to clean
* @returns {string} - The cleaned domain string
*/
export const cleanDomainInput = (input) => {
return input
.replace(/^(https?:\/\/)?(www\.)?/i, '')
.replace(/\/+$/, '')
.trim();
};
/**
* Validate domain format using regex
* @param {string} domain - The domain to validate
* @returns {boolean} - Whether the domain format is valid
*/
export const isValidDomainFormat = (domain) => {
if (!domain) return false;
return /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/.test(domain);
};
/**
* Validate domain availability with API
* @param {string} domain - The domain to validate
* @param {string} type - The domain type ('domain' or 'subdomain')
* @returns {Promise} - Promise resolving to validation result
*/
export const validateDomainAvailability = async (domain, type) => {
try {
const response = await fetch('http://localhost:2058/host-api/v1/validate-domain/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ domain, type })
});
if (!response.ok) {
console.error(`Network error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return {
isValid: data.status === "success",
message: data.status === "success"
? 'Domain is valid and registered.'
: 'Domain appears to be unregistered or unavailable.'
};
} catch (error) {
console.error('Error validating domain:', error);
return {
isValid: false,
message: `Error checking domain: ${error.message}`
};
}
};
/**
* Copy text to clipboard
* @param {string} text - Text to copy
* @returns {Promise} - Promise resolving to success or error
*/
export const copyToClipboard = async (text) => {
try {
await navigator.clipboard.writeText(text);
return { success: true };
} catch (err) {
console.error('Failed to copy:', err);
return { success: false, error: err.message };
}
};