Email address check in Javascript - javascript

I think many people have done some similar development tasks before:
I would like to check the people's email address whether only match #tomtom.com or #stream.com.
Currently, I have two solutions in my mind:
Using indexof() function
var checkTomTomEmail=eo.data.username.indexOf("#tomtom.com");
var checkStreamEmail=eo.data.username.indexOf("#stream.com");
if (checkTomTomEmail >0 || checkStreamEmail >0 )
{
//Run the login code
}
Else
{
//Please login with your tomtom or stream email
}
Using match
var patt1=/#tomtom.com/gi;
var patt2=/#stream.com/gi;
var checkTomTomEmail=eo.data.username.match(patt1);
var checkStreamEmail=eo.data.username.match(patt2);
if(indexOf(checkTomTomEmail)> 1 ||indexOf (checkStreamEmail)>1)
{
//Login
}
I still think I do not consider all the detail yet. Any suggestions?
Thanks

Perhaps if people are only allowed to enter emails for those two addresses you should only collect the username and then allow them to choose #tomtom.com or #stream.com using radiobuttons.
If you still want to go the javascript route then your regex can be combined into a single statement
var emailPatt=/#(tomtom|stream).com/gi;
if(emailPatt.test(eo.data.username))
{
//Login
}

How about this...
var emailRegex = /^([0-9a-z])+#(tomtom|stream)\.com$/ig;
if (emailRegex.test(emailRegex)) {
// Login
}
Instead of performing a .match(...) - Which you'll get a string back, we can perform a .test(...) to see if anything matches.
This pattern guarantees the following:
The "username" part of the email address must at least have a SINGLE character (For example, a#stream.com)
Username must be composed of a digit or an alphabet (Upper/Lower case - Doesn't matter because of the /i at the end)
Input must contain the entire email address without leading or tailing spaces. For example, " user#tomtom.com " will fail, it'll only accept "user#tomtom.com".)
You can customize this further by, saying, making sure username must have at least 3 characters, you can use underscore or dashes in the email address, etc.
To answer your question, both solutions won't work. Reasons:
User can enter "tom#tomtom.com Hello", and it'll pass both of your validation.
Specifically on solution #2, the dot '.' is a Regex-reserved character, it means it'll match anything, so, if the user enters " #tomtom1com", it'll pass...
More on Regex: http://www.regular-expressions.info/reference.html

Related

Looking for ways to validate a username

I'm trying to validate usernames when using a tag function against these criteria:
Only contains alphanumeric characters, underscore and dot.
Dot can't be at the end or start of a username (e.g .username / username.).
Dot and underscore can't be next to each other (e.g user_.name).
Dot can't be used multiple times in a row (e.g. user..name).
The username ends when there is a character other than the allowed characters (e.g. #user#next or #user/nnnn would only validate user as a valid username)
Another username can only be written after a space. (e.g. #user #next would validate two usernames while #user#next would only validate user)
I have tried this so far:
^(?=.{8,20}$)(?![.])(?!.*[.]{2})[a-zA-Z0-9.]+(?<![.])$ and have dealt the multiple usernames problem with for loops.
I was wondering what would be the best way to implement something like this (e.g. regex, for loops, combination). I tried using regex but realised it is very specific and can get complicated.
Use the following regex:
(?!\.)(?![a-zA-Z._]*(?:\._|_\.|\.\.))[a-zA-Z._]*[a-zA-Z_]
(?!\.): Negative lookahead assertion to ensure the name cannot begin with a '.'
(?![a-zA-Z._]*(?:\._|_\.|\.\.)): Negative lookahead assertion that the name does not contain ._ nor _. nor .. in succession.
[a-zA-Z._]*[a-zA-Z_]: Ensures the name is at least one-character long and does not end with ..
See Regex Demo
However, the results are not necessarily what you might expect since you want to stop scanning a name when you come to the first character that is not part of a valid name but you continue scanning looking for more valid names. So when the input is, for example, .user, you stop scanning when you see the . because you know that a name cannot begin with .. But you then resume scanning and still end up scanning user as a valid name.
let text = 'user user_xyx_abc user__def user_.abc user._abc user..abc user_abc. .user';
let regexp = /(?!\.)(?![a-zA-Z._]*(?:\._|_\.|\.\.))[a-zA-Z._]*[a-zA-Z_]/g;
let matches = text.matchAll(regexp);
for (let match of matches) {
console.log(match);
}
Ideally, your input would contain only a single user name that you are validating and the entire input should match your regex. Then, you would use anchors in your regex:
^(?!\.)(?![a-zA-Z._]*(?:\._|_\.|\.\.))[a-zA-Z._]*[a-zA-Z_]$
See Regex Demo
But given your current circumstances, you might consider splitting your input on whitespace, trimming extra whitespace from the beginning and end of the strings, and then use the above regex on each individual user name:
let text = 'user user_xyx_abc user__def user_.abc user._abc user..abc user_abc. .user ';
let names = text.split(/\s+/);
let regexp = /^(?!\.)(?![a-zA-Z._]*(?:\._|_\.|\.\.))[a-zA-Z._]*[a-zA-Z_]$/;
for (name of names) {
if (regexp.test(name))
console.log(name);
}

Comma separated email validation

I am using the following link for validating email:
http://jquerybyexample.blogspot.com/2011/04/validate-email-address-using-jquery.html
I am using this function to validate my email address using js:
validateEmail = (sEmail) ->
filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/
if filter.test(sEmail)
true
else
false
$(document).ready (e) ->
$("#invitation_form").submit ->
sEmail = $("#invitation_email").val().split(',')
email=0
for email in [0..sEmail.length]
if $.trim(email).length is 0
$("h2").append("<div class='alert alert-error'>Please review the problems below</div>")
$("#invitation_email").attr("placeholder", "Email can't be blank")
return false
if validateEmail(email)
else
alert sEmail
email++
# $("h2").append("<div class='alert alert-error'>Please review the problems below</div>");
# $("#invitation_email").val('')
# $("#invitation_email").attr("placeholder", "Please enter valid email")
# return false
This is validating my email properly if I put only one email. But in my email text field I have to put many comma separated emails and then validate each email individually. For that I had put split(','), and the added the for loop but the validation is not done properly. If I put 'example1#email.com, example2#email.com', then its going in the else block which is for invalid emails. In the alert I am getting the individual emails but not getting how to validate each email individually.
Can someone please help me in this?
Thanks in advance.
When you say this:
for email in [0..sEmail.length]
you're saying:
for email in an_array_of_numbers
so the email values inside that loop will be integers and integers aren't email addresses. You say that:
This is validating my email properly if I put only one email.
but that's not true, it fails with one email address or many as you can see in this demo:
http://jsfiddle.net/ambiguous/7LFus/
If you want to look at the email addresses in sEmail, then you want:
for i in [0...sEmail.length]
email = sEmail[i]
#...
or better:
for email in sEmail
#...
Note that the first version uses ... instead of your .., .. includes the upper limit so if sEmail.length is one you'd be iterating over [0, 1] rather than the [0] that would match the array's indexes. I'd go with the for email in sEmail version rather than worrying about indexes.
Also, String#split can take a regex as the splitting pattern so you could removing the leading and trailing whitespace while splitting:
sEmail = $("#invitation_email").val().split(/\s*,\s*/)
That way you don't have to $.trim inside the loop and you won't forget to trim when calling validateEmail.
While I'm here, Regexp#test returns true or false so you don't need to say:
if filter.test(sEmail)
true
else
false
you can simply say:
filter.test(sEmail)
So just a couple small changes and you should have something that is cleaner and works better.
Demo: http://jsfiddle.net/ambiguous/SzzXV/
Try using a while statement instead. Like this:
sEmailArray = $("#invitation_email").val().split(',')
i = 0
email = undefined
while email = sEmailArray[i]
if validateEmail(email)
else
alert email
i++

Validate an email address

How would I check that a user's email address ends in on of the three
#camel.com, #mel.com, #camelofegypt.com
This is my code so far, it just validates whether or not the user has provided any text
if ($.trim($("#email").val()).length === 0) {
alert('You must provide valid input');
return false;
I want to implement the email address validation into my code.
use the following regex:
var reg=/#(camel|mel|camelofegypt)\.com$/
reg.test(email)
This only validates if you email ends in one of the three above. If you want ot know general email validation, search the web. There are tons of those
As described in the library to regular expressions, it is difficult to truly validate an email address. However, the below taken from the above website will do a good job.
The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to. You can (but you shouldn't--read on) implement it with this regular expression:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Simple Regex:
\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b
Trade offs of validating email addresses:
Yes, there are a whole bunch of email addresses that my pet regex doesn't match. The most frequently quoted example are addresses on the .museum top level domain, which is longer than the 4 letters my regex allows for the top level domain. I accept this trade-off because the number of people using .museum email addresses is extremely low. I've never had a complaint that the order forms or newsletter subscription forms on the JGsoft websites refused a .museum address (which they would, since they use the above regex to validate the email address).
However, if you just want your specific domain this is definitely a possibility but it is not recommended to deny an email address because it fails these regular expressions.
Taking the above you could simply validate using the following Regex:
\b[A-Z0-9._%+-]+#(camel|mel|camelofegypt)\.com\b
or:
^[A-Z0-9._%+-]+#(camel|mel|camelofegypt)\.com$
The difference between these two regex are simple, the first regex will match an email address contained within a longer string. While the second regular expression will only match if the whole string is the email address.
JavaScript Regex:
/\b[A-Z0-9._%+-]+#(camel|mel|camelofegypt)\.com\b/i
or:
/^[A-Z0-9._%+-]+#(camel|mel|camelofegypt)\.com$/i
Special Note: You should likely allow for case insensitive with your regex using the i parameter since John#CAMEL.com is the same as john#camel.com. Which i've done in the above regex.
function ValidateEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
OR
This is a regular-expression email validation comparison that will test a bunch of valid/invalid email address against the regex provided by you in the textarea below.
^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$
Try out this javascript
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
Try this function,
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( $email ) ) {
return false;
} else {
return true;
}
}
if( !validateEmail(email)) { /* do stuff here */ }
var x=$("#email").val();
var n=x.split("#");
if($.inArray(camel.com,n)!= -1)//checks if camel.com is there in your email address if not the value will be -1 #is not given in front of camel.com because its split after # which means that #will be present before it if camel.com is prescent.
{
}
else
if($.inArray(mel.com,n)!= -1)
{}
else
if($.inArray(camelofegypth.com,n)!= -1)
{}
else
alert("");
using new regex
demo Here
added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
Note : Keep in mind that no 100% regex email check exists

Regular expression for multiple email addresses

I am working to validate a string of email addresses. This pattern works fine if there is only one email address:
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
But if I have two email addresses separated by space or by a newline, then it does not validate. For example:
xyz#abc.com xyz#bbc.com
or
xyz#abc.com
xyz#bbc.com
Can you please tell me what would be a way to do it? I am new to regular expressions.
Help much appreciated! Thanks.
Try this RegEx
/^\s*(?:\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}\b\s*)+$/
In the above image, everything inside Group 1 is what you already had. I have added a word ending and spaces.
It will match "xyz#abc.com", " xyz#bbc.com ", "xyz#abc.com xyz#bbc.com" and email addresses in multiple lines also.
Update
I got the RegEx for Email from http://www.regular-expressions.info/email.html and I have used it in my expression. You can find it below:
/^\s*(?:([A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4})\b\s*)+$/i
Change the ^ and $ anchors to word boundaries, \b.
/\b\w+...{2,3}\b/
You should also note that the actual specification for email addresses is extremely complicated and there are many emails that will fail this test -- for example those with multiple periods in the domain. May be okay for your purposes, but just pointing it out.
try this
function validateEmail(field) {
var regex=/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
return (regex.test(field)) ? true : false;
}
function validateMultipleEmailsCommaSeparated(value) {
var result = value.split(" ");
for(var i = 0;i < result.length;i++)
if(!validateEmail(result[i]))
return false;
return true;
}
You might consider simply splitting the whole string into an actual array of email addresses, instead of trying to validate the entire thing at once. This has the advantage of allowing you to point out in your validation message which address failed.
uld look like this:
var emailRegex = /^[A-Z0-9._%+-]+#(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i; // http://www.regular-expressions.info/email.html
var split = form.emails.value.split(/[\s;,]+/); // split on any combination of whitespace, comma, or semi-colon
for(i in split)
{
email = split[i];
if(!emailRegex.test(email))
{
errMsg += "The to e-mail address ("+email+") is invalid.\n";
}
}
Your best regular expression for multiple emails accepts all special characters
(-*/+;.,<>}{[]||+_!##$%^&*())
Best Regular Expression for multiple emails
/^([A-Z0-9.%+-]+#[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+#[A-Z0-9.-]+.[A-Z]{2,6}))*$/i

Email validation not accepting domains with only two characters

I am working with an email validation script and all is well, apart from if a user tries to enter an address with only two characters in the domain such as test#me.com or temp#ip.com
The validation then fires an error, I have looked through but cant see where this behaviour is being targeted, the code is below...
function validate_youremail()
{
var isvalidemailflag = 0;
if(jQuery("#property_mail_email").val() == '')
{
isvalidemailflag = 1;
}else
if(jQuery("#property_mail_email").val() != '')
{
var a = jQuery("#property_mail_email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
isvalidemailflag = 0;
}else{
isvalidemailflag = 1;
}
}
if(isvalidemailflag)
{
youremail.addClass("error");
youremailInfo.text("Please Enter valid Email Address");
youremailInfo.addClass("message_error2");
return false;
}else
{
youremail.removeClass("error");
youremailInfo.text("");
youremailInfo.removeClass("message_error");
return true;
}
Its probably staring me straight in the face but its been a long day :) Can anyone point me in the right direction?
#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+
Means "#" then "one or more of those characters" then "one or more of those characters and dots and hyphens" then "one or more of those characters".
That makes it "at least three characters".
You probably want to change the middle part (of that snippet) to be zero or more (i.e. * instead of +).
The expression is still broken though. The problem that jumps out at me is that it rejects email addresses with a + in the part before the #.
Email Validation as per RFC2822 standards.
Pattern: /[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g
Source: RegExr
Mind you, the RFC2822 standard doesn't allow upper case characters in an email address, but you can easily adapt it for your own purposes.
I recommend you to use another regular expression.
This regular expression has been extracted from the PHP source code written in C.
/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}#)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/i
.test('temp#ip.com');

Categories