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.
Related
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));
}
Tring to write php code to identify whether email id exists or not to prevent mail bounces. However below written code sometimes yields wrong results.
For example, I got mail bounce for michael#act-tec.com and alfiras#emirates.net.ae email ids. But when checked with below code, i get valid result for later one which is wrong and invalid result for first email id which is correct. I dont know what else check I am missing in this code. Tried many things from past 1 week but badly stuck. Please help
$isValid = 1;
$atIndex = strrpos($email, "#");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = 0;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = 0;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = 0;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = 0;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = 0;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = 0;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = 0;
}
else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))
{
$isValid = 0;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
// domain not found in DNS
$isValid = 0;
}
return $isValid;
}
You can check the email syntax and check if MX (Mail exchange) servers exists, but that is pretty much it.
You cannot be 100% sure that certain email account exists in the email provider.
Even dough when sending email to some account in the major email providers, they respond that certain email account exists and allow email to be sent. Later you may receive not delivered message
I'm trying to validate an input before I include another PHP so the user can get the error on the same page if there's one.. 4 inputs are required but the others are optional.. what I want to do is if the user only fill in the 4 required inputs validate the inputs than include another PHP file (instead of including the PHP I put a JavaScript instead to alert me that the code functions well..) and if the user also fill in the other optional inputs to also validate them and include a PHP file the problem I'm having is that it still alert me the code is good even when the user inserts invalid characters.
I only want it to process the last JavaScript if the user fills in the inputs with the allowed characters..
Here's the PHP:
<?php
// define variables and set to empty values
$titleErr = $MdescripErr = $posterErr = $vcodeErr = $vcode2Err = $vcode3Err = $mlink1Err = $mlink2Err = $mlink3Err = "";
$title = $Mdescrip = $poster = $comment = $vcode = $vcode2 = $vcode3 = $mlink1 = $comment = $mlink2 = $mlink3 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["title"]))
{$titleErr = "title is required";}
else
{
$title = test_input($_POST["title"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[A-Za-z0-9 ]*$/",$title))
{
$titleErr = "Only letters and white space allowed";
}
}
if (empty($_POST["Mdescrip"]))
{$MdescripErr = "Movie Description is required";}
else
{
$Mdescrip = test_input($_POST["Mdescrip"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[A-Za-z0-9 ]*$/",$Mdescrip))
{
$MdescripErr = "Only letters and white space allowed";
}
}
if (empty($_POST["poster"]))
{$posterErr = "Poster Link is required";}
else
{
$poster = test_input($_POST["poster"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$poster))
{
$posterErr = "Invalid URL";
}
}
if (empty($_POST["vcode"]))
{$vcodeErr = "Embed Link is required";}
else
{
$vcode = test_input($_POST["vcode"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$vcode))
{
$vcodeErr = "Invalid URL";
}
}
if (empty($_POST["vcode2"]))
{$vcode2 = "";}
else
{
$vcode2 = test_input($_POST["vcode2"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$vcode2))
{
$vcode2Err = "Invalid URL";
}
}
if (empty($_POST["vcode3"]))
{$vcode3 = "";}
else
{
$vcode3 = test_input($_POST["vcode3"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$vcode3))
{
$vcode3Err = "Invalid URL";
}
}
if (empty($_POST["mlink1"]))
{$mlink1 = "";}
else
{
$mlink1 = test_input($_POST["mlink1"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$mlink1))
{
$mlink1Err = "Invalid URL";
}
}
if (empty($_POST["mlink2"]))
{$mlink2 = "";}
else
{
$mlink2= test_input($_POST["mlink2"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$mlink2))
{
$mlink2Err = "Invalid URL";
}
}
if (empty($_POST["mlink3"]))
{$mlink3 = "";}
else
{
$mlink3 = test_input($_POST["mlink3"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$mlink3))
{
$mlink3Err = "Invalid URL";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($title == NULL || $Mdescrip == NULL || $poster == NULL || $vcode == NULL)
{
}
else if (!preg_match("/^[A-Za-z0-9 ]*$/",$title) ||!preg_match("/^[A-Za-z0-9 ]*$/",$Mdescrip) || !preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$poster) || !preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$vcode))
{
}
else
{
?>
<script>
alert("it went through");
</script>
<?php
}
?>
You should try to split the url and remove the unnecesary items like "https://" so you can take one url like "http://www.stackoverflow.com/bla/bla/bla" and split it into ["http","","www.stackoverflow.com","bla","bla","bla"]
And finally check if each element is set(valid), this will make your validation quite simple
Using JSLint I can't get my isEmailValid working, what is wrong with the code? I get different error messages like local was not defined before it was used or # invalid character or ^ is not enclosed but for the email it could have the symbol "^"?
function isEmailValid(email) {
"use strict";
var e = (email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/);
if (e.length !== 2) {
return false;
}
if (local.test(e[0])) {
return false;
}
if (e[0].length > 253) {
return false;
}
if ((e[0][0] === ".") || (/\.\./.test(e[0]))) {
return false;
}
if (domain.test(e[1])) {
return false;
}
if (e[1].length > 253) {
return false;
}
if (e[1][0] === "." || /\.\./.test(e[1]) || e[1][e[1].length - 1] === ".") {
return false;
}
return true;
}
Validate email addresses client-side with this regular expression:
/.#./
And then do the real validation server-side by sending an email to that address.
Working email addresses can and do exist that do not conform to any spec. There's no sense restricting users because their valid email address looks wrong, while at the same time allowing users to enter email addresses that look right, but are fake (eg, iwontgiveyoumyrealemailaddress#noreply.com looks real to a computer, but probably isn't).
Required reading
I would suggest using regex:
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);
}
See also: Validate email address in JavaScript?
You're getting the error about local because you're not actually declaring it as a local variable within the function.
var statements don't contain or use parenthesis. So, using them anyways as:
var e = (email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/);
Is equivalent to:
local = /[^\w.!#$%&*+-\/=?^_{|}~]/;
domain = /[^\w.-]/;
var e = (email.split("#"), local, domain);
e will then be set to the result of the parenthesis being evaluated, which simply contain operands for comma operators. So, the last line is equivalent to:
email.split("#");
local;
var e = domain;
And, as that doesn't seem to be what you wanted, you probably don't want the parenthesis:
var e = email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/;
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;
}