Rewrite regex to accept conditional terms - javascript

^([a-z0-9_\.-])+#[yahoo]{5}\.([com]{3}\.)?[com]{3}$
this currently matches xxxx#yahoo.com , how can I rewrite this to match some additional domains? for example, gmail.com and deadforce.com. I tried the following but it did not work, what am I doing wrong?
^([a-z0-9_\.-])+#[yahoo|gmail|deadforce]{5,9}\.([com]{3}\.)?[com]{3}$
Thank you in advance!

Your regex doesn't say what you think it says.
^([a-z0-9_\.-])+#[yahoo]{5}\.([com]{3}\.)?[com]{3}$
Says any characters a-z, 0-9, ., - one or more times.
That later part where you are trying match yahoo.com is incorrect. It says y, a, h, or o, any of those characters are allowed 5 times. Same with the com so aaaaa.ooo would be valid here. I'm not sure what the ([com]{3}\.)?[com]{3} was trying to say but I presume you wanted to check for .com.
See character classes documentation here, http://www.regular-expressions.info/charclass.html.
What you want is
^([a-z0-9_.\-])+#yahoo\.com$
or for more domains use grouping,
^([a-z0-9_.\-])+#(yahoo|gmail|deadforce)\.com$
You haven't stated what language you are using so a real demo can't be given.
Functional demo, https://jsfiddle.net/qa9x9hua/1/

Email validation is a notoriously difficult problem, and many people have failed quite horribly at trying to validate them themselves.
Filter var has a filter just for emails. Use that to check for email address validity. See http://php.net/manual/en/function.filter-var.php
if (filter_var('bob#example.com', FILTER_VALIDATE_EMAIL)) {
// Email is valid
}
There's probably no downside to doing the domain check the easy way. Just check for the domain strings in the email address. e.g.
if (
filter_var($email, FILTER_VALIDATE_EMAIL) &&
preg_match("/#(yahoo|gmail|deadforce)\.com/", $email)
) {
// Email is valid
}
In terms of your original regular expression, quite a lot of it was incorrect, which is why you were having trouble changing it.
regexper shows what you've created.
([a-z0-9_\.-])+ should be [a-z0-9_\.-]+ or ([a-z0-9_\.-]+)
The () are only capturing results in this section. If you want results move the brackets, if not remove them.
[yahoo]{5} should be yahoo
That's matching 5 characters that are one of y,a,h,o so it would match hayoo etc.
\.([com]{3}\.)?[com]{3} should be \.com
Dunno what this was trying to accomplish but you only wanted .com
Take a look at http:// www.regular-expressions.info /tutorial.html for a guide to regular expressions

Related

Finding difficulty in correct regex for URL validation

I have to set some rules on not accepting wrong url for my project. I am using regex for this.
My Url is "http ://some/resource/location".
This url should not allow space in beginning or middle or in end.
For example these spaces are invalid:
"https ://some/(space here in middle) resource/location"
"https ://some/resource/location (space in end)"
"(space in starting) https ://some/resource/location"
"https ://(space here) some/resource/location"
Also these scenario's are invalid.
"httpshttp ://some/resource/location"
"https ://some/resource/location,https ://some/resource/location"
Currently I am using a regex
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
This regex accepts all those invalid scenarios. I am unable to find the correct matching regex which will accept only if the url is valid. Can anyone help me out on this?
We need to validate n number of scenarios for URL validation. If your particular about your given pattern then above regex expression from other answer looks good.
Or
If you want to take care of all the URL validation scenarios please refer In search of the perfect URL validation regex
/(ftp|http|https){1}:\/\/(?:.(?! ))+$/
is this regex OK ?
use this
^\?([\w-]+(=[\w-]*)?(&[\w-]+(=[\w-]*)?)*)?$
See live demo
This considers each "pair" as a key followed by an optional value (which maybe blank), and has a first pair, followed by an optional & then another pair,and the whole expression (except for the leading?) is optional. Doing it this way prevents matching ?&abc=def
Also note that hyphen doesn't need escaping when last in the character class, allowing a slight simplification.
You seem to want to allow hyphens anywhere in keys or values. If keys need to be hyphen free:
^\?(\w+(=[\w-]*)?(&\w+(=[\w-]*)?)*)?$

Regex for combination of given rules

I'm trying to write regex to validate the password for the given rule.
Passwords must be at least 8 characters in length and contain at least 3 of the following 4 types of characters:
lower case letters (i.e. a-z)
upper case letters (i.e. A-Z)
numbers (i.e. 0-9)
special characters (e.g. !##$&*)
I was going through this discussion and found this really great answer over there.
Now I'm trying to write regex for the mentioned requirements and I came up with the solution like this
^(?=.*[A-Z])(?=.*[!##$&*])(?=.*[0-9])(?=.*[a-z]).{8,}|
(?=.*[!##$&*])(?=.*[0-9])(?=.*[a-z]).{8,}|
(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,}|
(?=.*[A-Z])(?=.*[!##$&*])(?=.*[a-z]).{8,}|
(?=.*[A-Z])(?=.*[!##$&*])(?=.*[0-9]).{8,}$
and it is working perfect see rubular but I want to optimize these regex and I'm not sure If there are any way to simplify this.
Any suggestion will be appreciated.
Many thanks
Do yourself (and anyone who will work on that app in the future) a favour, and split the regexp in 4:
{
:lowercase => /regex_for_lowercase/,
:uppercase => /regex_for_uppercase/,
:digits => /regex_for_digits/,
:symbols => /regex_for_symbols/,
}
then count how many of these 4 rules the password matches. It will also give you the chance to show more helpful error message if the entered password does not validate.

Surname regular expression

I'm trying to create a good regular expression for people's Surname.
It should be valid if a Surname is:
abcd
abcd'efg
abcd-efg
abcd, .efg
etc...
I also need to test if symbols do not repeat... so for example:
abcd''efg
abcd-',
Are invalid but the one:
abcd, .efg
Can be valid.
At the moment I just created this:
^[a-z .',-_]+$
And now I'm trying to check for all the double symbols but I cannot go ahead successfully.
It's a bad idea. There is no international list of allowed characters that people could use in their names. Some surnames even contain Unicode symbols — it will not be possible to write a regex that would perfectly validate all of them correctly. Even if you can come up with a regex, it might be too generic that it wouldn't be effective.
Read this article for why you shouldn't be doing this: Falsehoods Programmers Believe About Names
If after reading this insightful post by Amal Murali and you still want to do this with a regex, please see this:
/^(?![^'\-_\n]*['\-_][^'\-_\n]*['\-_])[a-z .',-_]+$/m
View a regex demo!

JQuery/javascript email validation with regex [duplicate]

This question already has answers here:
How can I validate an email address using a regular expression?
(79 answers)
Closed 8 years ago.
I have been searching around a bit for a good regex for email validation, but for most of the ones I am finding I see the people comment saying the regex is outdated, or it doesn't work... so I am hoping that someone can help me out with an email validation regex that is currently valid for all emails...
here's what I have so far : I have seen people saying that emailReg2 is outdated and produces false positives, but haven't seen anything about emailReg1 being outdated.
var emailReg1 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,6})?$/;
var emailReg2 = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
function IsEmail(email) {
var regex = //which regex do I put here?
return regex.test(email);
}
any clarification is greatly appreciated. Thanks!
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
For a regex to validate email addresses, you should look at your needs and determine if you do need something complex or something very simple.
For a simple (and hackish) regex:
.+?#.+?\..+
Going indepth:
.+? # At least 1 or more character, non-greedy; matches everything before the # sign
# # literal #
.+? # Same as above; matches everything before the .
\. # literal .
.+ # match everything after
This doesn't work for domains like appname.appspotmail.com as it has multiple fullstops in it, but should suit your needs.
You can modify the above regex to accept such conditions. As mentioned, it all depends on your needs. There is no better or worse regex for email validation; there is only a regex that meets your needs perfectly and a regex that is unnecessarily verbose.
If possible, you should come up with your own regex instead of using others, as you're the only person who will know your own needs.
If you must use something that complies with the RFC, look at this extremely verbose regex: http://ex-parrot.com/~pdw/Mail-RFC822-Address.html However, I would discourage you from using that regex and instead look for a library that validates email addresses. You probably don't need to comply with the RFC, though.
If you want resources for debugging regular expressions, give http://regex101.com a try.
The REGEX I use for Email validation is
^[a-zA-Z][\w\.-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$
There are a number of REGEX questions on SO for the Best Email Validation.
Best Regular Expression for Email Format Validation with ASP.NET 3.5 Validation
Validate email address in JavaScript?
Using a regular expression to validate an email address
From most of my research you will find plenty of REGEX that will validate most email addresses, but I have never found one that will catch all emails. You have to find the one that fits your needs the best.

regular expression with if statements

I have this as my regular expression:
var email = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
And this is my if statement:
if($('#email').val() ==""){
$('#emailErrorMsg').text("Please enter a valid email address.");
}
else if(!email.test('#email')) {
$('#emailErrorMsg').text("OK");
}
else($('#emailErrorMsg').text("Please enter a valid email address."));
});
When I type in a valid email address it says "OK". However, if I enter just some text for example it still says "OK" when I want it to say "Please enter a valid email address". Anyone any idea. By the way, I'm still an amatuer at this stuff!
The main problem is that you have a ? at the end of the regex, following parentheses that enclose the entire pattern. This effectively makes the entire match optional, so the regex will literally match anything.
Note also that you are testing the literal string #email, not the value of the #email element. Make sure you pass the appropriate string to test().
I see that you have jquery tag, so take a look to JQuery validate plugin, it will be better than a simple regex.
But if you still want regex, see Validate email address in JavaScript?
Validating emails is hard. The fully correct regex is a true monstrosity that you can see (if you dare) at http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html which probably isn't what you want.
Instead, you have a few options. Use a regex that matches 99% of emails, do it server side with an email validation library, or implement a finite state machine to parse it correctly. The state machine is probably too bulky (although allows neat stuff like suggestions for possible typos) and doing it all server side -- which you better be doing anyway (what if someone has JavaScript disabled?) -- loses the benefits of as-you-type checking.
That leaves a simpler regex that doesn't match all legal emails, but matches enough that the chances of someone registering with one that it doesn't are really slim.
The regex from Validate email address in JavaScript? should do the trick pretty well:
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
Also, you made a small typo:
else if(!email.test('#email')) {
$('#emailErrorMsg').text("OK");
}
is testing against the string '#email' -- not the element with the ID 'email'. Change that to:
else if(!email.test($('#email').val())) {
$('#emailErrorMsg').text("OK");
}
There's a little typo in your regex. Try this:
var email = /^([\w-\.]+)#([\w-]+\.)+[\w-]{2,6}?$/;
That should also handle the .museum case

Categories