Javascript email regex matching - javascript

Please see the Javascript code below. The else if block which is doing a check for email pattern is not allowing any of the email ids . What does the match() function return? Please help.
Used test()
empty field :working fine
wron mail id : working fine
Correct email id : not working
var pattern = new RegExp("/^(([^<>()[\]\\.,;:\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,}))$/");
if(!accountantEmail){
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").show();
$("#accountantEmailInvalidFormat").hide();
$("#accountant_email").focus();
return false;
}
else if(!(pattern.test(accountantEmail))){
$("#accountantEmailInvalidFormat").show();
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").hide();
$("#accountant_email").focus();
return false;
}

Javascript match returns an array containing the matches.
Here's the regular expression I use:
var pattern = "[-0-9a-zA-Z.+_]+#[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}";
if(!(accountantEmail.match(pattern))) {
return false;
}

For validation scenarios, you should use the RegExp#test function.
var pattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (!pattern.test(accountantEmail)) {
$("#accountantEmailInvalidFormat").show();
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").hide();
$("#accountant_email").focus();
return false;
}
As commented on the other posts, the match function is intended for group capturing.
Also note that you were specifying your pattern with an / on it's beginning. This isn't necessary if you're specifying a RegExp as a string.

Related

JavaScript split string around emails

So I have this list of emails:
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
john.doe#doe.com
It comes through as a string, sometimes with a return character at the end of each line, sometimes it doesn't. All I want to be able to do is pull out each email from the string using regex.
So I've got this regex exp from here:
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);
}
How do I get it to match many email addresses and return me each individual email?
I do not want to split on a return character, I can't always garauntee that it will be that character that will split the list up. These emails are pasted in from the users clipboard. If it were that easy, I wouldn't have asked ;)
It comes through as a string, with a return character at the end of
each line.
Then just split the string on newlines ?
var email_array = str.split("\n");
Here's a VERY simple way to do it.
/([^;:<>!?\n]+\#[^;:<>!?\n]+\.[^;:<>!?\n]+)/gmi
Explanation:
The [^;:<>!?\n] matches everything EXCEPT those characters. So [^;:<>!?\n]+ just means match everything but these as many times as needed.
Then match an # symbol.
Then match as many of NOT these ([^;:<>!?\n]) as needed again.
Then match a literal dot (.).
Then DON'T match these ([^;:<>!?\n]) again.
The gmis at the end are called flags. They mean:
g means global. Match this RegEx over and over.
m means multi-line. Don't stop at the end of the first line of emails.
i means insensitive. Don't worry about the upper and lower cases.
Demonstrations here: https://regex101.com/r/aC5cK2/1
So I have re work the answer to incorporate what #adeneo said:
$scope.pasteThis = function(e) {
var emails = e.clipboardData.getData('text/plain');
var emailArray = emails.split(/(\n|\s|,)/);
angular.forEach(emailArray, function (e) {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+#[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
if (EMAIL_REGEXP.test(e)) {
if (!contains($scope.emailAddresses, e)) {
$scope.emailAddresses.push(e);
}
}
});
}
function contains(arr, el) {
var found = false;
angular.forEach(arr, function(e) {
if (e == el) {
found = true;
}
});
return found;
}
So EMAIL_REGEXP is from the Angular source code. I use that in other places so it is very appropriate to use it here (consistency).
This function makes sure that after the emails are split, each one is a valid email address. This means that no mess can get through.

jQuery regex validation of e-mail address including blank value

I am using custom[email] rule for email validation in Jquery Validation Engine. What I want is, I want regex that validates email with blank value also. If value is blank then also it should show error message.
I dont want to use required rule.
Here is the custom rule given in Jquery Validation Engine
"email": {
// HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 )
"regex": /^(([^<>()[\]\\.,;:\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,}))$/,
"alertText": "* Invalid email address"
}
Please help me out.
This should work
^([^#]+#[^#]+)?$
It will validate
empty strings, OR
strings that have one or more non-#
followed by a #
followed by one or more non-#
try this
here is the fiddle
var emailReg = /^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/;
function checkEmail(email) {
var reg1 = /(#.*#)|(\.\.)|(#\.)|(\.#)|(^\.)/; // not valid
var reg2 = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
if (!reg1.test(email) && reg2.test(email)) {
return true;
}
else {
return false;
}
}

phone number regex not working

I have a form with an input that follows this pattern:
pattern='(\+|00)\d{2,3}[-]\d{8,10}'
an example would be +999-123456789
I have to form validate it again using javascript and have tried to convert the pattern into a Regex, the example passes the pattern but fails passing the regex. Any idea as to why?
var check = /^([00|+])([0-9]{2,3})[-]?([0-9]{8,10})$/;
Your regular expression is incorrect. This:
[00|+]
is equivalent to
[0|+]
and means "match a single character that's either '0', '|', or '+'." I think you want:
var check = /^(00|\+)(\d{2,3})-(\d{8,10)$/;
Here is your pattern tranferred to a RegEx: /(\+|00)\d{2,3}-{0,1}\d{8,10}$/. Example below.
var number = '+999-123456789';
if (number.match(/(\+|00)\d{2,3}-{0,1}\d{8,10}$/)) {
alert('Phone number valid!');
} else {
alert('Phone number invalid.');
}

javascript regular expression .search

i have a little problem with .search
this is the code
// filter - posts
jQuery('.filter_by').live('click',function(){
var target_fi = jQuery(this);
var target_cat = target_fi.parents('.cat').children('.namechanger').val();
target_fi.next().fadeIn(100);
var cat_all = target_fi.prev().find("option").each(function(i){
if(jQuery(this).attr('data-cats').search(target_cat) == -1){
jQuery(this).css({"display":"none"});
}
});
});
I want to use the variable target_cat with .search
I can't do this .search(/target_cat/)
If you want to make a regular expression out of the string value of target_cat, then you can do this:
var mySearchTerm = new RegExp(target_cat);
...
if(jQuery(this).attr('data-cats').search(mySearchTerm) == -1){
You need to create RegExp object and pass that to search method
if(jQuery(this).attr('data-cats').search(new RegExp(target_cat)) == -1 )){
...
}
To convert anything into a regular expression, simply drop it into the constructor:
var something = "foobar";
var expression = new RegExp(something, 'i');
note the second argument for flags. See RegExp for more info on the constructor and Regular Expressions for details on how things work.
If your something contains "special characters" (such as |, ?, {) you need to escape them, if you want them to be meant literally (/foo?/ vs. /foo\?/). Here's a function that'll esacpe all relevant characters for you:
function escapeRegEx(string) {
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
You are using jQuery.live, but should use jQuery.on instead
You are using .search() when .match() suffices
You are using the explicit jQuery(this).css({"display":"none"}); when jQuery(this).hide(); suffices
note that you are repeating jQuery(this) in your loop - one should be enough - variables are your friends.

Why does this jQuery code not work?

Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions

Categories