How to validate multiple emails at once in Javascript? - javascript

I'm working on validating multiple emails from an input field and can't really get my Regex to work. I have an input field that has emails separated by a comma, semi-colon, space and sometimes no space, something like this:
user1#email.comuser2#gmail.com , user3#email.com;user4#gmail.com user5#email.com
I'm trying to get all emails using Regex and then validate each of them, but not really sure how to do it using Regex in Javascript.
I have written my code in Java and it works great at getting all emails:
Java code:
String employeeEmails = "user1#email.com , user2#gmail.com user3#email.com;user4#gmail.com";
Matcher eachEmail = Pattern.compile("\\w+#\\w+.com").matcher(employeeEmails);
List<String> emailList = new ArrayList<String>();
while (eachEmail.find()){
emailList.add(eachEmail.group());
}
Finally emailList has all the emails
Now I'm trying to get all emails in Javascript and validate each of them and if one of them is not a valid email throw an error. Here's my code:
Javascript:
var regex1 = /\w+#\w+.com/; // This will get all emails from inputField
var emailList = regex1;
var regex2 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/; // This will validate each email
for(var i = 0;i < emailList.length;i++) {
if(!regex2.test(emailList[i])) {
return me.invalidText; // throw error if an email is not valid
}
}
Need to get this done in Javascript. Can anyone tell me what I'm missing please? Thank you in advance!

I hope this help you:
employeeEmails = "user1#email.com , user2#gmail.com user3#email.com;user4#gmail.com*john#doe";
function extractEmails(x) { return x.match(/([\w-\.]+)#((?:[\w]+\.)+)([a-zA-Z]{2,4})/g); }
var emails=extractEmails(employeeEmails);
// The emails already in an array, now a more exhaustive checking:
function validateEmail(v) { var 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,}))$/;
return regex.test(v);
}
emails.forEach(function(email, index)
{
// Here you can handle each employee emails.
//
// Example:
var verified=validateEmail(email);
document.write(' validation is '+ verified +' for '+ email +'<br>');
});
Sources:
How to validate email address in JavaScript?
https://www.w3schools.com/js/

Related

Validating UK PostCode with JavaScript Reg for Angular5 app

I am working on Angular 5 Reactive Form validation and trying to validate UK PostCode using custom validation function which is working and testing apart from in case provide extra letter or numeric value at end of postcode 2nd part, it validate true, for example NW10 5NW is correct but if I type anything like NW10 5NWRRRRRRRRRRRRRRRR is also return true which is not correct.
I have tried following regular experssion on https://regexr.com/ and it return correct response, not sure why in javaScript not behaving same way???
function postCodeValidator(control: FormControl)
{
let givenPostCode = control.value;
let UKPostCodePattern = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})/;
var isUKPostCodeValid = UKPostCodePattern.test(givenPostCode);
console.log("postcode validity ",isUKPostCodeValid, " for ", givenPostCode);
if(!isUKPostCodeValid)
{
return {
postCode:{
required:"UK Valid PostCode",
provided: givenPostCode
}
}
}
return null;
}
Try using following regex
^(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2}))$
https://regexr.com/3pp3r

Javascript Function to Obscure Email Using Asterisks?

I'm working on a password reset page where a user types in their username. I'd like to let them know what email it was sent to (sometimes we forget what email we used), without revealing too much information.
So rather than showing: joe_awesome#example.com I'd like to do the following: jo*********#example.com in javascript.
How would I do this efficiently? Basically I'd only like to show the first two letters and the domain only.
P.S. I'm new to javascript. Thanks!
Assuming your email is well formatted and the name has at least 3 characters the solution bellow should work.
var email = "joe_awesome#example.com";
function formatEmail(emilString){
var splitEmail = emilString.split("#")
var domain = splitEmail[1];
var name = splitEmail[0];
return name.substring(0,3).concat("*********#").concat(domain)
}
console.log(formatEmail(email));
In case you want the strings to have the same lengths although i don't recommend it.
function formatEmailSameLength(emilString){
var splitEmail = emilString.split("#")
var domain = splitEmail[1];
var name = splitEmail[0];
return name.substring(0,3).concat(Array(name.length-3).join("*")).concat("#").concat(domain)
}
Just a different answer
const maskEmail = (mail) => {
let mailUsername = mail.split("#")[0];
mailUsername = mailUsername[0] + mailUsername.substring(1).replace(/./gi, '*')
let mailDomain = mail.split("#")[1].split(".")[0].replace(/./gi, '*');
let mailTld = mail.split("#")[1].split(".")[1].replace(/./gi, '*')
return `${mailUsername}#${mailDomain}.${mailTld}`
}

Javascript method to check for digits within a string (validation of input data)

Im trying to implement a validation for an input field in IBM BPM.
Im not really familiar with java script but I try to get method that returns
ture if a string contains any numbers.
awdadw = valid
awdawd2d = invalid
I tried this method:
function hasNumbers(t)
{
var pattern=new RegExp("^[A-Za-z]+$");
return pattern.test(t); // true if string. Returns false for numbers
}
When I try this function, it says that method / variable RegExp is unknown. Since it is rather basci stuff I hope to get some sources where this topic is explained.
You can use this:
function validate(){
var re = /^[A-Za-z]+$/;
if(re.test(document.getElementById("inputID").value))
alert('Valid Name.');
else
alert('Invalid Name.');
}
Based on adre3wap this worked for me:
function validate(t){
var re = /^[A-Za-z]+$/;
if(re.test(t))
return false;
else
return true;
}

Regular expression validation - initialization error in Javascript

I am trying to write a function in Javascript to validate email address. Here is the function.
function validateEmailAddress() {
var patternForEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/;
var regexPatternForEmail = new RegExp(patternForEmail, 'i');
// Email address and the Confirm Email address values should match
if ($('#txtEmail').val() != $('#txtConfirmEmail').val()) {
$('#dvErrorMsg').html("Email addresses do not match.");
$('#txtEmail').focus();
return false;
}
else if (!regexPatternForEmail.test($('#txtEmail').val())) {
$('#dvErrorMsg').html("Please enter a valid email address.");
$('#txtEmail').focus();
return false;
}
else
return true;
}
The problem here is I am getting an error, 'Syntax error in regular expression' during RegExp object instantiation.
I tried debuggin in IE 11 and that's where i found the error.
Could someone please suggest me a solution for this.
Screen shot taken while debugging:
You don't need to create another regex variable using RegExp constructor. Just use only the below.
var patternForEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/i;
i at the last called case-insensitive modifier which helps to do a case-insensitive match.
Example:
> var patternForEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/i;
> patternForEmail.test('foo#bar.com')
true
> patternForEmail.test('#foo#bar.com')
false
In most of the times this kinds of errors occurs because of browser compatibility , so always we need to use the codes which can be run in all the browsers. I hope the following changes will help you.
var patternForEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
then you can match the expression using
if (patternForEmail.test($('#txtEmail').val())) {
$('#dvErrorMsg').html("Please enter a valid email address.");
$('#txtEmail').focus();
return false;
}
or else you can use match() function also which will be more flexible for all the browsers.
var email = $('#txtEmail').val();
if (!email.match(/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i)) {
$('#dvErrorMsg').html("Please enter a valid email address.");
$('#txtEmail').focus();
return false;
}

Code won't run due to string length issue

Got a simple Javascript program here to accept and check a password. It should:
Ask you to enter a new password
Check the strength of the password which outputs a message of either weak or strong based on a length of <6 or >6.
Get you to re enter this password to enter the 'system'
Give you simple prompts or 2 random letters if the password is not correct.
Everything works except the strong/weak checker. It has a problem getting the length of passwordEntry since it apparently doesn't exist as an entity.
Any ideas would be much appreciated
var pass;
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
var strengthCheck = new function(passwordEntry){
score = 0;
// adds to the score variable depending on the length of the password
if(passwordEntry.length > 6{
score=(score+1);
}
//reads messages back stating how strong password is based on length
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
var passContinue = prompt("Do you want to continue with this password? Yes or no?")
if(passContinue === "no" || passContinue === "No"{
main();
}
else{
pass = passwordEntry;
console.log("Your new password has been changed to " + pass);
passwordChecker(prompt("Thank You. Please Enter Your Password Below"));
}
}
var passwordChecker = function (attempt){
if(attempt == pass){
console.log("Correct password. The system has logged you on");
}
else{
//if the password is wrong, runs the incorrectpassword() function
console.log("Incorrect Password");
IncorrectPass();
}
}
}
var IncorrectPass = function (){
var clueanswer = prompt("Do You Want A Clue");
if(clueanswer === "Yes" ||clueanswer === "yes"){
console.log("I will give you two random letters");
// takes two random locations from the string array and reads them back
var randarray1 = Math.floor((Math.random()*7)+1);
var randarray2 = Math.floor((Math.random()*7)+1);
var randletter1 = pass[randarray1];
var randletter2 = pass[randarray2];
console.log(randletter1+" "+randletter2);
passwordChecker("Please try entering your password again");
}
else{
console.log("GoodBye");
}
}
main()
This part looks very wrong:
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
You should use == or === instead of = which is used for assignment rather than comparison.
This doesn't make sense either:
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
There are three opening parentheses and only two closing ones. Smells like parser error.
Change this...
var strengthCheck = new function(passwordEntry){
to this...
var strengthCheck = function(passwordEntry){
When you use new, you're not using it to create a new function. You're using it to call the function as a constructor, which will return an object. (An empty object in your case.)
Also, you have many syntax errors in your code. Use a code validator like http://jshint.com as well as a beautifier like http://jsbeautifier.org to clean up your code.

Categories