Validate/accept only emails from a specific domain name - javascript

This is part of my jQuery script. I need to make the system validate emails for a specific domain.
like example#schooldomain.com
And only allow emails from #schooldomain.com
Code:
email: function(value,element){return this.optional(element)||/^((([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(value);}

Firstly, as pointed out in the comments, validate the email using regex, and then check if the email is from the right domain.
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)){
//Email valid. Procees to test if it's from the right domain (Second argument is to check that the string ENDS with this domain, and that it doesn't just contain it)
if(email.indexOf("#thedomain.com", email.length - "#thedomain.com".length) !== -1){
//VALID
console.log("VALID");
}
}
}

Thanks to this thread I found another solution for only accepting one specific domain after the "at" / "#". Get everything after the dash in a string in JavaScript
Basically dividing the email in two, the text before # and the text after #. If the text after # is not equal to the specified domain the validation will be false.
// Email validation
let em = document.forms['Login']['email'].value;
let atpos = em.indexOf("#");
let domain = em.split("#")[1]; // Saves user input after the # (at)
if (em == null || em == "") {
alert("Email can not be empty.");
document.getElementById('e').focus();
return false;
}
// First test checks for atleast one character before #
else if (atpos < 1 || domain != "gmail.com"){ // Second test checks if the user entered a gmail.com domain after #
alert("Not a valid e-mail address. Please write your gmail address like this: username#gmail.com.");
document.getElementById('e').focus();
return false;
}

Related

Regex that validates both IPv4 address and domain name

if (isValidDomainName(addr)) {
return true;
}
else if (isValidIPv4(addr)) {
return true;
}
function isValidIPv4(addr){
var regex = /^((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])$/;
return regex.test(addr);
}
function isValidDomainName(name){
var regex =/^((www\.([a-zA-Z0-9\-]{2,63}\.)+[a-zA-Z]{2,63})|(([a-zA-Z0-9\-]{2,63}\.)+[a-zA-Z]{2,63}))(\.[a-zA-Z]{2,63})?$/;
return regex.test(name);
}
This is the code I have written. I am facing some issues. Let me give some examples:
google.com - valid domain name(expected)
192.15.67.34 - valid ipv4 address(expected)
192.45.dd.33
EXPECTED : invalid ip
ACTUAL :Valid domain name because the current system validates it as it passes the domain name constraint
192.67.77.xx
EXPECTED : invalid ip
ACTUAL :Valid domain name because the current system validates it as it passes the domain name constraint
Please pour in some valuable comments.
To the best of my knowledge, a domain name can be any sequence of "blocks" comprised of a combination of ASCII letters, digits and symbol -, blocks being separated by .. It can be maximum 255 characters long and must end with a primary domain name.
Given that primary domains could be anything defined as block up there, by this definition, 192.45.dd.33 and 192.67.77.xx are valid domain names.
Why don't you validate your input as an IP address, and then validate it as domain only if it's not recognized as a valid IP ?
function isValid(addr) {
if (isValidIPv4(addr)) {
return true;
} else if (isValidDomainName(addr)) {
return true;
}
return false;
}
function isValidIPv4(addr){
var regex = /^((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])$/;
return regex.test(addr);
}
function isValidDomainName(name){
var regex =/^((www\.([a-zA-Z0-9\-]{2,63}\.)+[a-zA-Z]{2,63})|(([a-zA-Z0-9\-]{2,63}\.)+[a-zA-Z]{2,63}))(\.[a-zA-Z]{2,63})?$/;
return regex.test(name);
}
for (addr of [
'192.168.1.52','192.168.1.xx', '192.ww.1.0', '255.255.255.000',
'my-domain.com', 'my$IPp.com', 'google.192'
]) {
console.log(addr, isValidIPv4(addr), isValidDomainName(addr), isValid(addr));
}

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;
}

Email validation for specific domains

I need help in email validation, this validation code all email in specific format like, test#test.gov.au, test#something.ac.au and i want it to be allowed in format test#something.au
(Note : Here I am only allowed to get entry for 5 domains that is gov.au, edu.au, govt.nz, ac.au and csiro.au)
My code is as follow
JS:
function emailTldValidation(tlds) {
$.validator.addMethod("emailTld", function(value,element) {
if (value.search("#") != -1) {
return (/(.+)#(.+)\.(gov\.au|edu\.au|ac\.nz|csiro\.au|govt\.nz)$/).test(value);
//return (/(.+)#(.+)\.(csiro\.au|gov|gov\.us)$/).test(value);
}
return false;
},"Please enter valid tld like "+tlds);
$.validator.addClassRules({
stringInput: {
emailTld: true
}
});
}
And the following code is validate in function.php
function validateEmail($email) {
//validate email here from server side
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate tld
$validTlds = str_replace(".", "\.", VALID_EMAIL_TLDS);
$validTlds = "\.".str_replace(",", "|\.", $validTlds);
$emailArr = explode("#", $email);
$emailTld = $emailArr[1];
if (preg_match('/^[-a-z0-9]+\.[a-z][a-z]|('.$validTlds.')\z/', strtolower($emailTld))) {
//check main domain here
$exValidTlds = explode(",", VALID_EMAIL_TLDS);
$exValidTlds = array_map('trim', $exValidTlds);
foreach($exValidTlds as $tld) {//if exist then
if(strstr($emailTld, ".".$tld)) {
if($tld == strrchr($emailTld, $tld)) {
return true;
}
}
}
return false;
}
}
function validateEmail($email) {
//validate email here from server side
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate tld
$validTlds = str_replace(".", "\.", VALID_EMAIL_TLDS);
$validTlds = "\.".str_replace(",", "|\.", $validTlds);
//$validTlds = str_replace(",", "|\.", $validTlds);
$emailArr = explode("#", $email);
$emailTld = $emailArr[1];
if ($emailTld == 'csiro.au')
{
//check main domain here
return true;
}
elseif (preg_match('/^[-a-z0-9]+('.$validTlds.')\z/', strtolower($emailTld))) {
//check main domain here
$exValidTlds = explode(",", VALID_EMAIL_TLDS);
$exValidTlds = array_map('trim', $exValidTlds);
foreach($exValidTlds as $tld) {//if exist then
if(strstr($emailTld, ".".$tld)) {
if($tld == strrchr($emailTld, $tld)) {
return true;
}
}
}
return false;
}
}
return false;
}
This regexp worked pretty well for me:
.+#(?:(?:govt*)|(?:edu)|(?:ac)|(?:csiro))\.(?:au|nz)
I used this tool to create it: http://regexpal.com/
FYI, validating email is incredibly difficult: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
Edit: After re-reading your question, it seemed like you might need validation for emails with subdomains and such as well. This is probably better suited for more open ended domains:
.+#(?:\w+\.\w+)
Edit 2: So the problem is that your validation is too light for your complexity.
.+#(?:(?:.+\.(?:(?:govt*)|(?:edu)|(?:ac))\.(?:au|nz))|(?:csiro\.au))
Breaking it down:
.+ // Match at least 1 of any character
# // An # symbol
(?: // The group of everything right of the # symbol
(?: // The group of domains that have subdomains
.+\. // At least one character in front of a .
(?: // govt, edu or ac
\. // a dot
(?: // au or nz
(?: // or simply 'csiro.au'
You can't get around the fact that four of your domains need a subdomain, and one does not.

How to check specific email validation in phonegap android

I had created an registration form in which i had created and email i had provided validation to all the filed but I'm confused how to give validation to email field because i want that email should be either gmail.com or yahoomail.com if some one enters any other email even yahoomail.co.in it should give error message.
here is the code i which checking that its having # and . in the email or not
var atdrate=email.indexOf("#");
var dot1=email.indexOf(".");
else if(atdrate<1 || dot1<1)
{
alert("Enter valid Email");
if(gml<atdrate+1)
alert("Enter a vaild mail id");
else if(yml<atdrate+1)
alert("Enter a valid email id");
}
Using Regular Expressions is probably the best way. Here's an example (live demo):
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);
}
But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.
*answer from https://stackoverflow.com/a/46181/1521984
Update: Then use the JavaScript split() function to split the mail address after the '#' and check the value versus your strings.
var mail = yourMailAdress.split("#");
if (mail[1] == "gmail.com" || mail[1] == "yahoomail.com") {
// OKAY
} else {
// false
}

test javascript string for complete URL to PDF

I have a form where I would like the user to input a complete URL that leads directly to a PDF (not a page that contains a pdf).
Currently I am testing (and adding if necessary) for http/https link this:
var str = textfield.value;
//test for http/https and add it if not there
var httpsInc = str.indexOf('https://') !== -1;
var httpInc = str.indexOf('http://') !== -1;
if ((httpsInc == false) & (httpInc == false)) {
textfield.value = "http://" + str;
var str = textfield.value;
}
and then testing that it is a valid URL (based on another post on here):
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
testresults=1;
} else {
testresults=0;
}
return (testresults);
I was then going to add in the test for .pdf [something like str.indexOf('.pdf') !== -1] but I figured there must be a better way to do this. The RegExp above could likely do all of this testing for me I assume (test that .pdf is at the end etc), but I am unsure how to modify it. Is it better to modify it or just check that the last 4 characters of my string are ".pdf"?

Categories