format & validate multiple email addresses from textarea - javascript

I need to trim out white space and separate with semicolons. When thats done validate email addresses are in a proper email format before I pass into the database. Something like this:
"tom#yahoo.com;bob#yahoo.com"

Here's on I did in JavaScript using jQuery Validate:
$.validator.addMethod('emailList', function(value, element) {
if (this.optional(element)) return true;
var flag = true;
var addresses = value.replace(/\s/g,'').split(',');
for (i = 0; i < addresses.length; i++) {
flag = /^((([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.test(addresses[i]);
}
return flag;
}, '');
You can change the split to ; if that's your delimiter.

http://www.regular-expressions.info/email.html
That has a lot of information on regular expressions and email. I would use a simple split.
http://www.somacon.com/p355.php
Removing White space

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.

Javascript validation of special characters in textbox and textarea

I need to add validation to textbox and textarea to validate them against the following rules upon submit (ampersand and apostrophes are allowed). //,./,/.,/*,*.,~,\\
I tried the following code
alert("is valid "+ isValid("mhse sn hs ~"));
function isValid(value)
{
return !/[~//./*././*\\]/i.test(value);
}
the above code will return false because ~ is in this code but if i try / this will return false so i think problem in grouping characters.
1) write one javascript function which eliminates special charactors
function isValid(str){
var iChars = "#$%&"; // type your excepting keys here
var flag = true;
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
flag = false;
}
}
return flag;
}
2) check your entered value with isValid() function like below
isValid("hye!##~%^&*)");
Answer: if you entered special chars is there, then flag will returns false.
when you escape, you do it carefully :D
for matching * or . literally, you need to escape them
the corrected version will be
/[~/\/\.\/\*\./\.\/\*\\]/.test(".");

Explode JavaScript regular expression for password strength

I have a regular expression used to check my password validity (I found it in the internet). It checks the minlenght of 6 characters, at least one upper, at least one lower, at least one number, and a symbol. I want to explode this regex and put it in an array so that I can check the passwords strength.
var regexp = /^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%!]).{6,})$/
Then I'll have something like this:
if(regexparray[0].test(passwordval)){
strenght++;
} else if(regexparray[1].test(passwordval)){
strenght++;
}
//etc....
EDIT: What is the proper way to divide this regex into its parts?
Extending Jorge Campos's comment, you could do something like this:
var passwordval = 'fdSfdDSF';
var tests = [
'(?=.*\d)',
'(?=.*[a-z])',
'(?=.*[A-Z])',
'(?=.*[##$%!])',
'.{6,}'
],
strength = 0;
for (var i=0, l=tests.length; i<l; i++) {
var re = new RegExp(tests[i]);
if (re.test(passwordval)) {
strength += 1;
}
}
console.log(strength);
// 4
If you're grabbing user input from a form field you're probably already sanitizing the input a bit by doing something like var passwordval = $.trim($('#password').val());. Plus, you don't really need to restrict the tests with start and end of string metacharacters (^ and $).

string with valid characters only without regex

Suppose I have a string containing "hello, world!" and another one with "hello world", I want my function to return false for the first and trye for the second, by basically checking it against an array of valid characters, for example a-z.
Problems is I do NOT want to use a regex. I could use .indexOf but it only works for ONE character.
Any way to do this, possibly in a non-blocking way (using node.js)?
Thanks in advance.
In PHP, I used to do something similar:
$sUser = 'my_username01';
$aValid = array('-', '_');
if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
echo 'Your username is not properly formatted.';
}
function hasBadChars(s) {
var badChars = ['!'],
i;
for (i = 0; i < s.length; ++i) {
if (badChars.indexOf(s[i])) {
return true;
}
}
return false;
}
console.log(hasBadChars('Hello world!'));

Javascript IndexOf with integers in string not working

Can anyone tell me why does this not work for integers but works for characters? I really hate reg expressions since they are cryptic but will if I have too. Also I want to include the "-()" as well in the valid characters.
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
Review
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
This String "method" returns true if str is contained within itself, e.g. 'hello world'.indexOf('world') != -1would returntrue`.
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
The value of $('#textbox1').val() is already a string, so the .toString() isn't necessary here.
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
This is where it goes wrong; effectively, this executes '1234'.indexOf('0123456789') != -1; it will almost always return false unless you have a huge number like 10123456789.
What you could have done is test each character in str whether they're contained inside '0123456789', e.g. '0123456789'.indexOf(c) != -1 where c is a character in str. It can be done a lot easier though.
Solution
I know you don't like regular expressions, but they're pretty useful in these cases:
if ($("#textbox1").val().match(/^[0-9()]+$/)) {
alert("valid");
} else {
alert("not valid");
}
Explanation
[0-9()] is a character class, comprising the range 0-9 which is short for 0123456789 and the parentheses ().
[0-9()]+ matches at least one character that matches the above character class.
^[0-9()]+$ matches strings for which ALL characters match the character class; ^ and $ match the beginning and end of the string, respectively.
In the end, the whole expression is padded on both sides with /, which is the regular expression delimiter. It's short for new RegExp('^[0-9()]+$').
Assuming you are looking for a function to validate your input, considering a validChars parameter:
String.prototype.validate = function (validChars) {
var mychar;
for(var i=0; i < this.length; i++) {
if(validChars.indexOf(this[i]) == -1) { // Loop through all characters of your string.
return false; // Return false if the current character is not found in 'validChars' string.
}
}
return true;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.validate(validChars)) {
alert("Only valid characters were found! String validates!");
} else {
alert("Invalid Char found! String doesn't validate.");
}
However, This is quite a load of code for a string validation. I'd recommend looking into regexes, instead. (Jack's got a nice answer up here)
You are passing the entire list of validChars to indexOf(). You need to loop through the characters and check them one-by-one.
Demo
String.prototype.Contains = function (str) {
var mychar;
for(var i=0; i<str.length; i++)
{
mychar = this.substr(i, 1);
if(str.indexOf(mychar) == -1)
{
return false;
}
}
return this.length > 0;
};
To use this on integers, you can convert the integer to a string with String(), like this:
var myint = 33; // define integer
var strTest = String(myint); // convert to string
console.log(strTest.Contains("0123456789")); // validate against chars
I'm only guessing, but it looks like you are trying to check a phone number. One of the simple ways to change your function is to check string value with RegExp.
String.prototype.Contains = function(str) {
var reg = new RegExp("^[" + str +"]+$");
return reg.test(this);
};
But it does not check the sequence of symbols in string.
Checking phone number is more complicated, so RegExp is a good way to do this (even if you do not like it). It can look like:
String.prototype.ContainsPhone = function() {
var reg = new RegExp("^\\([0-9]{3}\\)[0-9]{3}-[0-9]{2}-[0-9]{2}$");
return reg.test(this);
};
This variant will check phones like "(123)456-78-90". It not only checks for a list of characters, but also checks their sequence in string.
Thank you all for your answers! Looks like I'll use regular expressions. I've tried all those solutions but really wanted to be able to pass in a string of validChars but instead I'll pass in a regex..
This works for words, letters, but not integers. I wanted to know why it doesn't work for integers. I wanted to be able to mimic the FilteredTextBoxExtender from the ajax control toolkit in MVC by using a custom Attribute on a textBox

Categories