How can I validate the comma separated urls in a way that accepts subdomains, localhost and allows whitespace before or after the comma? Here’s an example of how I’d like this to work:
const regEx = regex; // working regular expression here
console.log(regEx.test('localhost:3000')); // should return true
console.log(regEx.test('https://google.com,https://jeith.com')); // should return true
console.log(regEx.test('subdomain.jeith.com, localhost:3000')); // should return true
console.log(regEx.test('jeith com')); // should return false because of whitespace not near comma
console.log(regEx.test('jeith.com,,localhost:3000')); // should return false because of double comma
I have an input requesting URLs separated by commas. Usually for something like this, I would split the string by commas and perform the url validation on the individual URLs, but I’m unable to do in this project as I’m doing the validation via zod.
This doesn't need to be very strict, and validation for .com, .net, http://, ect isn't needed.
I'm a beginner with regex and this is closest I can get to this validation: /^[A-Za-z] (?:\s*,\s*[A-Za-z] )*$/
. What's missing in this expression is the ability to accept : and . for https:// and .com. Other than that, it is successfully returning false if they're double commas present or whitespace away from the commas.
CodePudding user response:
Take a look at the link below, she already does this and presents you step by step.
RegExr: validation url:
[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\ ~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\ .~#?&//=]*)
CodePudding user response:
I would take a more naive approach otherwise you'll have to write a complex regex and it's extremely complex to validate a URL.
Best use the built in URL class.
const data = [
'localhost:3000',
'https://google.com,https://jeith.com',
'subdomain.jeith.com, localhost:3000',
'jeith com',
'jeith.com,,localhost:3000'
];
for(const item of data) {
const isValid = item
.split(',')
.every(url => {
try {
let cleanedUrl = url.trim();
// URL class requires that the given string includes a protocol
if(!cleanedUrl.startsWith('http')) {
cleanedUrl = 'http://' cleanedUrl;
}
if(!cleanedUrl || (/\s /g).test(cleanedUrl)) {
return false;
}
new URL(cleanedUrl);
return true;
} catch(err) {
return false
}
});
console.log(isValid, item);
}