How to validate email domains dynamically in Javascript - javascript

How to validate domains dynamically in javascript?
I have requirement where I need to validate domains (dynamically coming from other input) if it is matching the domain which we are getting from the company name selected then say valid. If it's not matching the domain should say like invalid domain.
For ex: if the
company name is XYZ allowed domain is : #xyz.com
company name is abc allowed domain is : #abc.com
so likewise when we change the company name the domain will change according to company selected.
How can we validate these domains dynamically ?
Below have code which will validate when we have one domain. Can someone help to get the domain validation dynamically?
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,}))$/;
if(re.test(email)){
if(email.indexOf("#gmail.com", email.length - "#gmail.com".length) !== -1){
console.log("VALID");
}
else {
console.log('INVALID');
}
}
}
validateEmail('zk#gmail.com'); //VALID
validateEmail('zk#mail.com'); //INVALID

If you need to match single domain
function validateDomain(email, companyName){
let match = email.match(/^\w+#(\w+).\w+$/);
return match!==null && match[1]===companyName;
}
validateDomain('gk#gmail.com','gmail') //returns true
validateDomain('gk#gmail.com','email') //returns false
validateDomain('gk.com','gmail') //returns false
If you need to match array of domains
function validateDomain(email, companyNameArr){
let match = email.match(/^\w+#(\w+).\w+$/);
return match!==null && companyNameArr.includes(match[1]);
}
validateDomain('gk#gmail.com',['gmail','yahoo']) //returns true
validateDomain('gk#gmail.com',['email','yahoo']) //returns false
validateDomain('gk.com',['gmail','yahoo']) //returns false

Why not use string functions instead?
return email.indexOf(domain) < 0
But if you insist with using the Regexp, it would be around like this:
var regex = new RegExp("\\w+#"+domain+"\\.\\w+");
return regex.test(email);

I found the below solution and it works.
function validateDomain(email, companyName){
return companyName.some((val) => email.includes(val))
}
console.log(validateDomain('lk#gmailL.com', ['gmailL.com', 'gmail.com','fa.com']));

Related

remove email address format from username

var login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.substring(0, login_id.lastIndexOf("#")));
Above script works perfectly if I pass input with '#abc.com'. Does not work if string do not have '#domain.com'
We have some user name with username#domain.com and few are just username. I want extract #domain.com from user name. Expected output is if input is username#domain.com return output = username and if input is username, output should be username.
Please help if there is any way.
Use .split() method to split your string in parts
It will still work if you do not have #domain.com
Case-1:
const login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"
Case-2:
const login_id = 'sa-testaccount0125';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"
If you split on # then you get an array of items. The first item of the array will be the username, whether there was a # in it or not.
const test = str => str.split('#')[0]
console.log(test('sa-testaccount0125#abc.com'));
console.log(test('sa-testaccount0125'));
You're already using a indexOf. Usee that to check # if exists as well:
function check(login_id) {
if (login_id.indexOf('#') >= 0) {
return login_id.substring(0, login_id.lastIndexOf("#"));
}
return login_id;
}
console.log(check('sa-testaccount0125#asdasdasd.com'));
console.log(check('sa-asd'));
console.log(check('sa-asasd#domain.com'));
check first if it contains the '#' charactar first
login_id.includes('#') ? console.log(login_id.substring(0,
login_id.lastIndexOf("#"))) : console.log(login_id) ;
Running example
function username(login_id) {
return login_id.includes('#') ? login_id.substring(0,login_id.lastIndexOf("#")) : login_id ;
}
console.log(username("sa-testaccount0125#abc.com")) ;
console.log(username("sa-testaccount0125")) ;

Validate domain name string with Javascript only .com and .net allowed

I have a function that validates domain names perfectly, but I need it to validate only ".com" and ".net'"s.
So a string "abcdefghi.co" or "abcdefghi.org" would be invalid.
Please give me a hand modifying the reg.
function frmValidate( domain ) {
if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/.test(domain)) {
//alert("Valid Domain Name");
return true;
} else {
//alert("Enter Valid Domain Name");
return false;
}
}
Because you only want to permit one . (followed by .com or .net), don't repeat the (?:\. ... group - instead, just match \., followed by a group that alternates between com and net. You may also simplify the pattern by using the case-insensitive flag /i:
/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]\.(?:com|net)$/i
const input = prompt('Domain to test?');
console.log(
/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]\.(?:com|net)$/i
.test(input)
);
The regex is currently testing if there's "." followed by 2 or more characters at the end.
Change it to ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:.(com|net))+$ and it will match only .com and .net domains
https://regexr.com/49fcn
// 1) there could be more than one dot in a valid domain name,
// since subdomains don't make domain names invalid;
// 2) for the dot(s) placement, don't use some reg ex wizardry
// that will confuse and confound the next support guy
// (even if that's only you six months later)
function frmValidate( domain ) {
// since domain could have subdomain like qwe.asd.zxc,
// parse into substrings at "."
var dParts = domain.split('.');
// capture tld from end of list
var tld = dParts[dParts.length - 1];
// determine whether tld is "com" or "net"
var isValid = ('com' === tld) || ('net' === tld);
// for testing
// alert('top level domain is: ' + tld + ' and is ' + (isValid?'':'NOT ') + 'valid');
// advise caller
return isValid;
};

JQuery check if a domain name contains .com or .net

I have a form where a user can enter a domain name, I want to validate if they have entered a domain that has .com or .net.
So,
www.example.com Or www.example.net //returns True
http://www.example.com/ Or http://www.example.net/ //returns True
www.example.au //returns False
www.example.com.au Or www.example.net.au //returns False
example.com Or example.net //returns True
I tried this:
var domain = "www.example.com";
if(domain.match(/([a-z])+\.(com|net)+/igm)) {
console.log(domain+" valid domain");
} else {
console.log(domain+" Invalid domain");
}
This works but it also shows domain www.example.com.au as valid.
Is there a better way to do this ?
Use regex to check if the URL ends with domain.
/\.(com|net)\/?$/i
$ will check if the string ends with the previous characters.
Code:
var domain = "www.example.com";
if (/\.(com|net)\/?$/i.test(domain)) {
console.log(domain + " valid domain");
} else {
console.log(domain + " Invalid domain");
}
A generic jquery function you can use for multiple purposes. tlds defaults to .com or .net, but you can supply an array of tld's for other uses
$.testDomain = function(domain, tlds) {
return new RegExp('\\.(' + (tlds || ['com', 'net']).join('|') + ')\\/?$', 'i').test(domain);
};
console.log($.testDomain('http://www.example.com/'));
test for .gov
console.log($.testDomain('http://www.example.gov/', ['gov']));
of course, it doesn't have to be tacked on to jQuery, just answering the question as asked
var testDomain = function( ...
then use
testDomain(...

I would like to use JQuery to validate a form unsing .inArray() and .val()

The script below is suppose to insert a message using .insertAfter() if a user doesn't type in an # symbol within a field . This script also displays an error message if the user types in a value that matches a value from the invalidEmailAddresses array.
For some reason only the second part of this script executes.
If a user types in an # symbol they get a message but if the user types in an address similar to test#yahoo.com a message doesn't display. Not sure if i organized the code correctly.
$(document).ready(function(){
$("input[name='emailAddress']").blur(function(){
// Actual Email Validation function
var hasError = false;
var emailaddressVal = $("input[name='emailAddress']").val();
var invalidEmailAddresses =
['goddady.com', 'aol.com', 'yahoo.com', 'yahoo.fr'];
if ($.inArray(emailaddressVal,invalidEmailAddresses) > 0) {
$( "<span id='emailMessage'>The email provided is not from a business related domain. Please use an appropriate email address instead.</span>" ).insertAfter( "input[name='emailAddress']" );
} else {
$ ('#emailMessage').css('display','none');
}
if ($("input[name='emailAddress']").val().indexOf('#') > -1) {
$ ('#emailMessage').css('display','none');
}
else {
$( "<span id='emailMessage'>The email provided does not contain an # symbol</span>" ).insertAfter( "input[name='emailAddress']" );
}
if(hasError == true) { return false; }
});
});
This is working if you add the following code
$(document).ready(function() {
$("input[name='emailAddress']").blur(function() {
// Actual Email Validation function
$('#emailMessage').html("");
var hasError = false;
var emailaddressVal = $("input[name='emailAddress']").val().trim();
var invalidEmailAddresses = ['goddady.com', 'aol.com', 'yahoo.com', 'yahoo.fr'];
if (!isValidEmailAddres(emailaddressVal)) {
$("<span id='emailMessage'>The email provided does not contain an # symbol</span>").insertAfter("input[name='emailAddress']");
hasError = true;
} else {
debugger
emailaddressVal = emailaddressVal.split('#').slice(1)[0].trim();
if ($.inArray(emailaddressVal, invalidEmailAddresses) >= 0) {
$("<span id='emailMessage'>The email provided is not from a business related domain. Please use an appropriate email address instead.</span>").insertAfter("input[name='emailAddress']");
} else {
$('#emailMessage').css('display', 'none');
}
}
if (hasError == true) {
return false;
}
});
function isValidEmailAddres(emailID) {
var regexExp = 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 regexExp.test(emailID);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="emailAddress" />
The issue lies with this if conditional: if ($.inArray(emailaddressVal,invalidEmailAddresses) > 0).
Since the $.inArray() method returns the index of a string found, when a value of 0 is returned, it is actually found—but at the start of the string (position 0, because JS is zero-based). So, you should use !== -1 instead, i.e.: if ($.inArray(emailaddressVal,invalidEmailAddresses) !== -1).
However, this does not completely solve your issue — $.inArray() only compares string, it does not search for it. Therefore if your string contains the blacklisted email domains, but does not match exactly, it will return false. In this case, you should use regular expression instead. The strategy is simple: use .each() to loop through your array, and take the value, use it to construct an expression which we will test your email address that is provided against.
Also, since there is the possibility that the user-entered email address fails both tests, two <div> of identical IDs will appear. This is invalid HTML. Instead, try using a class instead.
p/s: I also recommend changing listening to .blur() to .change() instead. It is more robust :)
With all the points above considered, I have refactored your code a little:
Declare a global (but still within function scope) error array called hasError. It will be used to store all error messages you get, since we cannot be sure if there will be one, or more than one error.
We construct two tests:
To test if email matches against blacklist using the string.search(regexp) method. If there is a match, the value returned will exceed -1. We then push the relevant error message into hasError in an object
To test if email contains the # sign, we use your default logic (which works beautifully). If there is an error, we push, again, the relevant error message into hasError in an object
At the end, we evaluate hasError. If it is not empty, then we know there is an error somewhere, and loop through it. The error messages are accessible via the messages keyword :)
Without further ado, here's your code:
$(document).ready(function() {
$("input[name='emailAddress']").change(function() {
// Actual Email Validation function
var hasError = [],
emailaddressVal = $("input[name='emailAddress']").val(),
invalidEmailAddresses = ['godaddy.com', 'aol.com', 'yahoo.com', 'yahoo.fr'];
// Check against blacklist
$.each(invalidEmailAddresses, function(i, v) {
var pattern = new RegExp(v, 'i');
if (emailaddressVal.search(pattern) > -1) {
hasError.push({
'test': 'blacklist',
'message': 'The email provided is not from a business related domain. Please use an appropriate email address instead.'
});
}
});
// Check if there is an '#' character
if ($("input[name='emailAddress']").val().indexOf('#') === -1) {
hasError.push({
'test': '# sign',
'message': 'The email provided does not contain an # symbol'
});
}
console.log(hasError);
// Error handling
$('#error').remove();
if(hasError.length > 0) {
var $error = $('<div id="error"><ul></ul></div>');
$.each(hasError, function(i,v) {
$error.find('ul').append('<li>'+v.message+'</li>');
});
$error.insertAfter("input[name='emailAddress']");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="emailAddress" type="email" />
</form>

Email validation Javascript+RegEx, but to exclude certain domains

I have client side email validation script Javascript+RegEx, it works fine, but I want to exclude certain domains while validating, namely all Apple domains since they do not work (emails sent to these addresses are deleted without any notice): #apple.com, #me.com, #icloud.com, #mac.com.
I found appropriate questions here, but still they are not the same I am asking for help.
Please, help to implement this
Can it be done via RegEx modification, or I have to use loop and search substrings (#apple.com, #me.com, #icloud.com, #mac.com) after the main email validation is done?
function verifyMe(){
var msg='';
var email=document.getElementById('email').value;
if(!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) ||
document.getElementById('email').value=='')
{
msg+='- Invalid Email Address: '+email+'\n\n';
document.getElementById('Eemail').style.color='#ffffff';
}
else
document.getElementById('Eemail').style.color='#bbb'
if(msg!='')
return false;
else
{
search_code(); //it's ok go ahead
return true;
}
}
Both approaches would work.
For the regex one, just insert the following part after the # in the regex (negative lookahead):
(?!(?:apple|me|icloud|mac)\.com$)
But a better regex overall would be:
^\w+[-\.\w]*#(?!(?:apple|me|icloud|mac)\.com$)\w+[-\.\w]*?\.\w{2,4}$
For the other approach, the following should work:
function isValidMailAddress(email) {
var match = /^\w+[-\.\w]*#(\w+[-\.\w]*?\.\w{2,4})$/.exec(email);
if (!match)
return false;
var forbiddenDomains = ["apple.com", "me.com", "icloud.com", "mac.com"];
if (forbiddenDomains.indexOf(match[1].toLowerCase()) >= 0)
return false;
return true;
}
It's up to you to decide which approach you feel most comfortable with.
You can use jQuery.inArray() for checking email with a specific domain name.
var email ="abc#xyz.edu.au"
var str = email.split('#').slice(1);
var allowedDomains = ['xyz.edu.au','abc.edu.au'];
if($.inArray(str[0], allowedDomains) === -1) {
alert('email is allowed.');
}
else{
alert('email not allowed.');
}
I updated #Lucas answer to match any type of country domain (apple.com, apple.de etc.).
Moreover it should be more robust because its closer to W3C standard: https://emailregex.com/
^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#(?!(?:yahoo|gmail|icloud|web|googlemail|aol|zoho|protonmail|outlook|hotmail|gmx|mail)[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]{1,10}$)[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$

Categories

Resources