Domain name regular expression - javascript

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.
Valid Domain:
api.google.com
*.api.google.com
*.api.google.user.com
tenant.my.centrify-kibble.net
aws.logs.security.stark.tony.com
myest.r-project.org
login-dev.qacloudad.com
Invalid Domain:
https://google.com
https://www.google.com
https://*.google.com
*.google.com/
*google.com/
*google.com
google.com.
login-dev.qacloudad.com.
login-dev.qacloudad.com.*
.login-dev.qacloudad.com
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");
}

You may use the following pattern:
^(?:\*\.)?[a-z0-9]+(?:[\-.][a-z0-9]+)*\.[a-z]{2,6}$
Regex demo.
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)
// ^

Related

Special characters should not be used continually

I'm creating regex for URL validation. Somehow i have validated Url as i need but my requirement was after the domain name https://asasas.com/ special character should not allow to be continually. Wanted to know how to restrict that?
My regex
Part 1 : (https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})
Part 2: [/]+[a-zA-Z0-9~##$!^%*;'&()<>_+=[]{}|\,.?: -]+.(?:jpg$|gif$|png$|jpeg$)/`
Part 1 regex to validate URL and Part 2 regex to validate string that it should end with .JPG or .PNG or .JPEG or .GIF
My requirement was it should not allow?
1) https://ssas.com//////////////////////////sds.png
2) https://ssas.com/sds//##$%/j^&&*///.png
Success case:
each and every special character it should have word or number
1) https://ssas.com/sds/sdsd/s#df^ggasa/dadsa.png
Instead of validating the whole url with a regex, you could first validate the url using URL.
Then you could check if the protocol starts with http and use a pattern to check if the string after the origin ends with one of the allowed extensions and that the string does not contain to consecutive chars which you would consider special.
If you want to get a case insensitive match, you could make use of the /i flag.
The pattern consists of 2 assertions (non consuming)
^(?=.*\.(?:jpe?g|png|gif)$)(?!.*[/~##$!^%*;'&()<>_+=\[\]{}|\,.?:-][/~##$!^%*;'&()<>_+=\[\]{}|\,.?:-])
In parts
^ Start of string
(?= Positive lookahead, assert what is on the right is
.*\.(?:jpe?g|png|gif)$ Match any of the listed at the end $ of string
) Close lookahead
(?! Negative lookahead, assert what is on the right is not
.* Match any char except a newline 0+ times
[/~##$!^%*;'&()<>_+=\[\]{}|\,.?:-] Match any of the listed
[/~##$!^%*;'&()<>_+=\[\]{}|\,.?:-] Same as above
) Close lookahead
Regex demo
[
"https://ssas.com//////////////////////////sds.png",
"https://ssas.com/sds//##$%/j^&&*///.png",
"https://ssas.com/sds/sdsd/s#df^ggasa/dadsa.png"
].forEach(s => {
let url = new URL(s);
let secondPart = url.href.replace(url.origin, '');
let pattern = /^(?=.*\.(?:jpe?g|png|gif)$)(?!.*[/~##$!^%*;'&()<>_+=\[\]{}|,.?:-][/~##$!^%*;'&()<>_+=\[\]{}|,.?:-])/i;
if (
url.protocol.startsWith("http") &&
pattern.test(secondPart)) {
console.log(s);
}
})

JavaScript Regular Expression Validation

I'm attempting to validate a field name to match a certain format in JavaScript using Regular Expressions.
I need the string inputted to resemble this:
word\word\word
So anything inputted can't be blank, and it must be three words seperated by a backslash.
This is the code i'm working with, but i'm not sure if the pattern is the right syntax?!!
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/[a-Z|/\\/|a-Z|/\\/|a-Z\s]/;
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
}
else
{
alert("match");
}
}
Any help will be very appreciated!!!
If by word you mean the English letters a-z in upper or lower case, then:
/^(?:[a-z]+\\){2}[a-z]+$/i
That says:
^ Beginning of string
(?:...) Non-capturing group
[a-z]+ One or more letters a-z (or A-Z because of the i flag at the end). If you also want to allow some other characters, just add them to the [a-z] after the z. If you want to allow hyphens, add \- to it (you need the backslash, depending on where you put the hyphen, so I just always include it). Note that this is very English-centric, and even in English sometimes people write borrowed words with their non-English letters, such as résumé.
\\ Backslash
{2} Repeated twice
(Then another word)
$ End of string
The issues with your expression are:
[a-Z] Is invalid because the range is out of order (Z comes before a). If it were valid (or if you wrote [Z-a]), it would matches everything between Z and a, which isn't just a-z and A-Z
\\/ Requires a backslash and then a slash
| is an alternation (this or that)
\s is whitespace
Try /^[a-z]+\\[a-z]+\\[a-z]+$/
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/^[a-z]+\\[a-z]+\\[a-z]+$/
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
} else {
alert("match");
}
}
If you want to allow the word matching to be case insensitive;
`/^[a-z]+\\[a-z]+\\[a-z]+$/i`
If you want to be a bit more broad with what you define as a 'word', and allow it to consist of alphanumeric characters and underscore;
`/^\w+\\\w+\\\w+$/i`
you can just use this \w+\\\w+\\\w+
or
[a-zA-Z]+(\\[a-zA-Z]+){2}
This should do it
^\w+\\\w+\\\w+$
In javascript
if (/^\w+\\\w+\\\w+$/.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
Try this one , See the Regex fiddle for regex demo and Jsfiddle for the code demo
Regex
/(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g
Javascript
function validateResourceName(string) {
var pattern = /(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g;
if (!pattern.test(string)) {
alert("not a match");
} else {
alert("match");
}
}

Javascript regex only alphabet, number and underscore

I want to check if a text box input is valid (only alphabet, numbers and underscores allowed. No whitespaces or dashes). I currently have this, but whitespaces & dashes seem to pass.
function validText(field)
{
var re = /[a-zA-Z0-9\-\_]$/
if (field.value.search(re) == -1)
{
alert ("Invalid Text");
return false;
}
}
A valid input would be something like
'Valid_Input123'
invalid
'Invalid-Input !'
The \w is a handy regex escape sequence that covers letters, numbers and the underscore character
You should test the entire string for valid characters by anchoring the validity test at the start (^) and end ($) of the expression
The regular expression test method is faster than the string search method
You can also test for one or more characters using the + quantifier
To summarise (in code)
var re = /^\w+$/;
if (!re.test(field.value)) {
alert('Invalid Text');
return false;
}
return true;
Alternatively, you can test for any invalid characters using
/\W/.test(field.value)
\W being any character other than letters, numbers or the underscore character.
Then you might also need to add a length check to invalidate empty strings, eg
if (/\W/.test(field.value) || field.value.length === 0)
You are only testing whether the text ends ($) with one of the characters in the character class. You are also explicitly allowing a dash (\-). If you don't want that, remove it.
Anchor the expression (^, $), add a quantifier (+) and .test whether the string only consists of those characters:
var re = /^[a-zA-Z0-9_]+$/; // or /^\w+$/ as mentioned
if (!re.test(field.value)) {
}
You forgot to anchor your regex at the beginning using ^
test is easier to use
There is no need for the dash.
It should look like this:
if (!/^[a-z0-9_]+$/i.test(field.value)) {
//
}
[\w]* will suffice.
Regex101 Example
This is a very basic Regular Expressions question
Learn more about regular expressions here: regular-expressions.info

Regular Expression for the given format - start and end with alphanumeric

I need to validate building name in the below format (length is 1-50)
my regex for alphanumeric and specified characters check
/^[a-zA-Z0-9\s\)\(\]\[\._-&]+$/
Its showing invalid expression but when i exclude & it works fine.
/^[a-zA-Z0-9\s\)\(\]\[\._-]+$/
Actual Format
Building name should use Letters, Numbers, Underscore_, Hyphen-, Period., Square-brackets[], Parentheses() ,Ampersand &
It should not start and end with any special characters continuously
Valid:
Empire3 State&Building[A]
7Empire.State-Building(A)
Empire(State)_Building[A]12
Invalid:
##$#$#building))
().-building2
$buildingseven[0]&.
i am struggling for 2nd format. how to check for continuous allowed special characters at first and last. Any help is very much appreciated.
Escape the - character:
/^(?!\W.+\W$)[a-zA-Z0-9\s\)\(\]\[\._\-&]+$/
In a character class, the - character signifies a range of characters (e.g 1-9). Because the ASCII code for & is less than _, your regular expressions fails to parse correctly.
Also, to check that no special characters are at the beginning or end, use \W (a character other than a letter, digit or underscore) in a lookahead to check that both the start and the end are not "special characters". If you count an underscore as a special character, use [^A-Za-z0-9] instead of \W.
var validBuildingName = /^(?!\W.+\W$)[a-zA-Z0-9\s\)\(\]\[\._\-&]+$/;
validBuildingName.test('(example)'); // false
validBuildingName.test('(example'); // true
validBuildingName.test('example)'); // true
validBuildingName.test('example'); // true

Alphanumeric email validation in javascript

I'm using a regex below to validate email to accept alphanumeric characters. It works in the following cases
1) Must contain atleast one alphabets
2) allow alphanumeric
3) allow special characters .-and _
Regular Expression:
/^([a-zA-Z0-9])(([a-zA-Z0-9])*([\._-])?([a-zA-Z0-9]))*#(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/i
Cases:
1111#gmail.com - allow
aaaa#gmail.com - allow
aa1_aa#gmail.com - allow
Output expected:
1111#gmail.com - not allow because it does not contain alphabets before #
aaaa#gmail.com - allow
a1#gmail.com - allow
1a#gmail.com - allow
aa1_aa#gmail.com - allow
Hers is jsfiddle Demo
Your regex will do the job, just add this at the beginning
(?=[^#]*[A-Za-z])
making your final regex like this:
/^(?=[^#]*[A-Za-z])([a-zA-Z0-9])(([a-zA-Z0-9])*([\._-])?([a-zA-Z0-9]))*#(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/i
(?=exp) is positive look-ahead. It will try to find the expression without taking it into match. look-ahead actually matches characters, but then gives up the match.
(?=[^#]*[A-Za-z]) : will match [^#]*[A-Za-z], meaning anything other than # followed by a alphabet. So actually it will match if at least one alphabet is present in the part before #
You canrefer this for look-ahead and look-behind
Here is the JavaScript code:
var email_to_check = "1111#gmail.com";
email_check=email_to_check.substring(0,email_to_check.lastIndexOf("#"));
var isnum = /^\d+$/.test(email_check);
var email_regex = /^([a-zA-Z0-9!##$%^&*(){}|:"<>?\/';\\+\-~]*#[a-zA-z]+\.[a-zA-z]+)$/;
email_test = email_regex.test(email_to_check);
if(isnum){
alert("You must enter aleast an Alphabet !")
}else{
if(email_test){
/* code if email is right :) */
alert("This is corrrect email !")
}else{
alert("Enter valid email address !");
}
}
Remove the special char which you don't want in your checklist.

Categories