Reputation: 491
I am trying to find if a string has valid domain names or not in JavaScript. As per requirement, these are my valid and invalid domain names.
below code is working as expected for both valid as well as invalid domain except "*google.com". I am still getting valid expression as result for "*google.com"
How can I fix this RegEx?
var fqdn = "aws.logs.security.stark.tony.com";
if (fqdn.match("^(?!-)[A-Za-z0-9-*]+([\\-\\.]{1}[a-z0-9]+)*\\.[A-Za-z]{2,6}$")) {
console.log("Matched");
}
else{
console.log("Not Matched");
}
Upvotes: 0
Views: 2220
Reputation: 19661
You may use the following pattern:
^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$
Breakdown:
^
- Beginning of string.(?:\*\.)?
- Match an optional "*." literally.[a-z0-9]+
- One or more alphanumeric characters.(?:[\-.][a-z0-9]+)*
- A hyphen or a dot followed by one or more alphanumeric characters to be matched zero or more times.\.[a-z]{2,6}
- A dot followed by between two and six letters.$
- End of string.JavaScript test:
var fqdn = "aws.logs.security.stark.tony.com";
if (fqdn.match(/^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$/)) {
console.log("Matched");
}
else{
console.log("Not Matched");
}
To support upper-case letters, you can either (re-)add A-Z
to the character classes or simply append the i
flag at the end:
fqdn.match(/^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$/i)
// ^
Upvotes: 3