jQuery regex validation of e-mail address including blank value - javascript

I am using custom[email] rule for email validation in Jquery Validation Engine. What I want is, I want regex that validates email with blank value also. If value is blank then also it should show error message.
I dont want to use required rule.
Here is the custom rule given in Jquery Validation Engine
"email": {
// HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 )
"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,}))$/,
"alertText": "* Invalid email address"
}
Please help me out.

This should work
^([^#]+#[^#]+)?$
It will validate
empty strings, OR
strings that have one or more non-#
followed by a #
followed by one or more non-#

try this
here is the fiddle
var emailReg = /^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/;

function checkEmail(email) {
var reg1 = /(#.*#)|(\.\.)|(#\.)|(\.#)|(^\.)/; // not valid
var reg2 = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
if (!reg1.test(email) && reg2.test(email)) {
return true;
}
else {
return false;
}
}

Related

Check if email has a certain domain or not

I am trying to add a check to see if an email (string) is part of a specific domain in google scripts. For example, the domain would be "#company.com", so all emails with this would pass the check and emails without it won't
basically what I have is a way to retrieve the current user's email using:
var email = Session.getEffectiveUser().getEmail();
Now I want to check this email for a specific domain/company
Example: abc#companyname.com
so in this case it would be the "#companyname.com" part
I know there usually is a way to do this in other languages but how can I do this in apps script?
Here's a function which uses a regular expression to match valid e-mails, and logs the result. Note that I'm using the i flag to do a case-insensitive search:
function emailCheck(email) {
var regExp = new RegExp("[a-z0-9\.-_]*#companyname\.com$", "i");
match = email.match(regExp);
if(match)
match = true;
else
match = false
Logger.log(email + ' - ' + match);
return match
}
The following inputs:
tests = ['ABC.345#companyNAME.com','no_no#goggle.com','ABC.345#companyNAME.com.edu']
for each (test in tests) {
emailCheck(test);
}
Output:
ABC.345#companyNAME.com - true
no_no#goggle.com - false
ABC.345#companyNAME.com.edu - false
You can test an email by using this simple regular expression:
/#company\.com$/
And with JavaScript you can use this true/false test:
/#company\.com$/.test(email)
Here is a working example:
const emailTest = email => /#company\.com$/.test(email);
['abc#company.com', 'abc#gmail.com', 'abc.123#gmail.company.com', 'defg#company.com', 'abc.123#company.gmail.com']
.forEach(email => console.log(email.padEnd(30), emailTest(email)))

Regular Expression in angular

I was creating a regular expression in angular to validate password which should have
A number
A uppercase letter
A lowercase letter
Only few symbols i.e !##$%
position of any character or symbol is not restricted.
I have tried this regex
/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/
But the above regex takes any special character to be valid... I just want !##$% this to be valid ele invalid
I'm not sure that all the things you want to do are possible in single regex. But you can use a simple validation function that uses some regex's:
function validate (pass) {
if (
/[A-Z]/.test(pass) && // uppercase letter is required
/[a-z]/.test(pass) && // lowercase letter is required
/[0-9]/.test(pass) && // number is required
/[!##$%]/.test(pass) && // predefined symbol is required
!/[^A-Za-z0-9!##$%]/.test(pass) // there is nothing unwanted
) {
return true;
}
return false;
}
Here is jsfiddle to show that it works.
Try a ng-change listener - something like the following HTML:
<input ng-model="pw" ng-change="checkPwPolicy(pw)">
<div ng-hide="passwordPolicyValid">Your password is too weak!</div>
Combined with this Javascript inside the scope of the controller of this form:
function checkPwPolicy(password) {
var valid = true;
// at least 1 number
valid = valid && password.match(/[0-9]/).length > 0;
// at least 1 uppercase
valid = valid && password.match(/[A-Z]/).length > 0;
// ...
$scope.passwordPolicyValid = valid;
}
Some things you could do to improve this implementation are that you could make the change listener fire less often, hide the error message when the password has not been touched, as well as adding more detailed errors to the password policy message.

REGEX in javascript not working for dots (.) in JavaScript

I am using a regex to validate an email address in JavaScript.
The regex is pretty simple. It checks three things: 1)'#' , 2)'.' ('dot' as in something#gmail.com), and 3) 'a-z' in an email address. If all three return true, email address is valid (according to my validation, atleast)
Here is the code:
function checkemail(){
var e = document.getElementById("email").value;
if((e.match(/#/g)==null)||(e.match(/[a-z]/ig)==null)||(e.match(/./g)==null)){
//display error message
}
}
My question is:
(e.match(/./g)==null); //returns false even though there are no dots in the string e
returns false even when there are no dots in string.
For example:
("thisIsMyEmail".match(/./ig))==null //returns false
Why does it return false when it should be true?
/./g (or /./ig) will match any string that as at least one character in it. . is special in regular expressions, it means "any character here."
For an actual dot, escape it with a backslash: /\./g.
First off, you don't need to check if the string is null. Simply use this:
var email = "Godisgood#gmail.com";
if (email.match(/^\S+\#\S+\.\S+$/i)){
alert("Email address passed validation.");
}
you have to escape the .
The unescaped period means matches any character.
Meaning having a string "abc" using your expression would result in an array containing the characters 'a', 'b', and 'c'.
In your snippet the correct answer is
(e.match(/\./g)==null);
This should result to what you're expecting
Try this
(e.match(/\./g)==null);
. matches any character so needs escaping /\./g
I know you have already got the answer.
But I just want to give an advice.
My advice is - don't use the javascript code to validate any email address; because as per your code, #domain., #domain.com these all are also valid email, but everybody knows these are not a valid email address.
So use the below code:
let email = $(this).val();
var positionOfAt = email.indexOf("#");
var positionOfDot = email.lastIndexOf(".");
if(email.search("#") == -1 || //if '#' is not present
email.search(" ") >= 1 || //if blank space is present
email.search(".") == -1 || //if "." is not present
positionOfAt < 1 || //if there is no character before "#", at least one character should be present before "#"
positionOfDot - positionOfAt <= 2 || //between '#' and '.', if there is not at least two character
email.length - positionOfDot <= 2) //if after '.' there is not at least two character)
{
console.log("Invalid email id")
}
else
{
console.log("Valid email id")
}

Why is my date validation not working?

My name, e-mail and check boxes follow the same js pattern and the validation works great but birthday will not validate. I start by stripping the white space so they can't leave it blank, then using a regex to determine if its valid. Is my regex wrong?
validate: function (attrs, options)
{
var errors = [],
pattern = '/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/',
isValidBirthday = attrs.birthday && attrs.birthday.replace(/\s/g, '') && attrs.birthday === ('pattern');
if (!isValidBirthday)
{
errors.push(
{
"birthday": "Must have a valid birth date."
});
}
if (errors.length)
{
return errors;
}
},
You are using the regular expression wrong. Try the following instead, noting the lack of
'' around the regex, and the use of .test method on the pattern.
var errors = [],
pattern = /^(0[1-9]|1[0-2])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$/,
isValidBirthday,
cleanedBirthday;
cleanedBirthday = attrs.birthday && attrs.birthday.replace(/\s/g, '');
isValidBirthday = pattern.test(cleanedBirthday)

Javascript email regex matching

Please see the Javascript code below. The else if block which is doing a check for email pattern is not allowing any of the email ids . What does the match() function return? Please help.
Used test()
empty field :working fine
wron mail id : working fine
Correct email id : not working
var pattern = new RegExp("/^(([^<>()[\]\\.,;:\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(!accountantEmail){
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").show();
$("#accountantEmailInvalidFormat").hide();
$("#accountant_email").focus();
return false;
}
else if(!(pattern.test(accountantEmail))){
$("#accountantEmailInvalidFormat").show();
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").hide();
$("#accountant_email").focus();
return false;
}
Javascript match returns an array containing the matches.
Here's the regular expression I use:
var pattern = "[-0-9a-zA-Z.+_]+#[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}";
if(!(accountantEmail.match(pattern))) {
return false;
}
For validation scenarios, you should use the RegExp#test function.
var pattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (!pattern.test(accountantEmail)) {
$("#accountantEmailInvalidFormat").show();
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").hide();
$("#accountant_email").focus();
return false;
}
As commented on the other posts, the match function is intended for group capturing.
Also note that you were specifying your pattern with an / on it's beginning. This isn't necessary if you're specifying a RegExp as a string.

Categories