regular expression with if statements - javascript

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

Related

How to remove an email from a string with JavaScript (GTM)

This might sound quite simple and since I'm not as experienced as I would like handling javascript, I want to remove an email from a string, actually is an error message while trying to login or sign up.
My errors look like this:
The following email xxxx#gmail.com is incorrect
Invalid Data
Must close the current session
Mail already registered
...
So the idea is to remove the email from the first error, and if there is no email present then leave the other errors as they are now.
I found this code to detect if there is an email in a string but can't find a way to make it work "([^.#\s]+)(\.[^.#\s]+)*#([^.#\s]+\.)+([^.#\s]+)"
I just want to send the data to google analytics, and I'm trying to avoid sending personal data.
Thanks in advance.
"([^.#\s]+)(\.[^.#\s]+)*#([^.#\s]+\.)+([^.#\s]+)" is a regular expression. It matches everything that looks like an email. You can use it with the replace() and search() JavaScript functions, you need to delimit the expression with two /.
Example:
var myString = "Hello, my email is blabla#blabla.com";
// Check if there is an email
if(myString.search(/([^.#\s]+)(\.[^.#\s]+)*#([^.#\s]+\.)+([^.#\s]+)/) !== -1){
console.log("There is an email !");
// Remove it...
myString = myString.replace(/([^.#\s]+)(\.[^.#\s]+)*#([^.#\s]+\.)+([^.#\s]+)/,"");
console.log(myString); // Hello, my email is
}
Good tutorial about JavaScript regular expressions: http://www.w3schools.com/js/js_regexp.asp

Rewrite regex to accept conditional terms

^([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

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.

Restrict input some personal information

I want to check what users type in Textarea.
Actually, how can I restrict typing phone numbers and e mail addresses in description box?
So for example:
Hi, I am selling a Bugatti Veyron
Age: 2010
Color: Black
You can contact me on 066/656-656 or 055646646
or via mail mesell#domain.com
If someone tries to enter something like this I want to automatically remove
personal contact details.
So, please help, how can I do it?
Use Regex and do something like this :
Here's an example (jsFiddle)
HTML
<textarea></textarea><br>
<button>Test</button><br>
<span class="result"></span>
Javascript:
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,}))$/;
$('.result').html(re.test(email));
if(re.test(email)){
$('.result').html("Contain email");
} else {
$('.result').html("Do not contain email");
}
}
$('button').click(function(){
validateEmail($('textarea').val());
});
Note that I only look for email. But you can use other Regex to look for phone, you just have to search for something like "javascript regex phone" on Google.
you can try Regex as suggested, but take into consideration it's very hard to stop a phone number from being entered(unless you stop ALL numbers or know the exact form of the number taking place).
For example, stopping a xxx-xxxxxxx number is easy, but the user can type each digit with a space after it, which makes it much harder to stop(unless you again remove the option to type numbers.
As for emails, a simple regex to find a # followed by some text, a dot and 2 or 3 characters normally finds emails pretty easily. be advised people can still be creative in the way they put their emails(AT instead of # for example).
this should all be done server side, you can use javascript on the clientside to make it UI friendly.
For email validation:
<input type="email" name="email">
Here is an example: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_type_email
For Phone number validation:
use regex, it should be straight forward though.
Or just try isNAN(value) where value is the phone number enterd, will tell you if this is a number of not and then you can also put a check on number of digits.
Hope this helps!

Email validation Javascript RegExp

With this RegExp I can easily check if an email is valid or not:
RegExp(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/);
However, this just return true for such addresses:
example#example.com
I also want to accept:
*#example.com
What changes I need to apply on my RegExp?
Thanks in advance
To answer your question literally, you can "augment" your regex:
RegExp(/^([\w.*-]+#([\w-]+\.)+[\w-]{2,4})?$/);
But this is a terrible regex for e-mail validation. Regex is the wrong tool for this. Why do you insist on doing it this way?
A couple of things: to accept *#foo.bar:
var expression = /^([\w-\.*]+#([\w-]+\.)+[\w-]{2,4})?$/;//no need to pass it to the RegExp constructor
But this expression does accept -#-.--, but then again, regex and email aren't all too good a friends. But based on your expression, here's a slightly less unreliable version:
var expression = /^[\w-\.\d*]+#[\w\d]+(\.\w{2,4})$/;
There is an expression that validates all valid types of email addresses, somewhere on the net, though. Look into that, to see why regex validating is almost always going to either exclude valid input or be too forgiving
Checking email addresses is not that straightforward, cf. RFC 822, sec 6.1.
A good list of regexes can be found at http://www.regular-expressions.info/email.html, describing tradeoffs between RFC conformance and practicality.

Categories