I am working on a lab for school where we create a function that validates that the email textbox value is a valid email structure (xyx#xyz.xyz). I am having trouble figuring out how it will work I am typing it in VS code and I'm not really getting anywhere when I load the page on Live Server. I am very new to JS so I feel like I am not implementing my function properly. Also, I used a simple Regex email pattern but am curious about how I can validate it with just vanilla javascript. Any help will be greatly appreciated. Thank you!
function validate(){
var email = document.getElementById("email").value;
var error = "";
const emailPattern =/\S+#\S+\.\S+/;
if(email.value.match(emailPattern))
{
return true;
}
else if(email.value == ""){
error = "You entered a blank email address. \n";
alert(error);
return false;
}
else
{
error = "You have entered an invalid email address!";
alert(error);
return false;
}
Creating a good regex for email is quite difficult for a novice because the email specification is quite permissive you can have multiple dots before and after the # and that's beside various disallowed characters.
You can google for proper regexes for email if required.
But you have multiple problems with your function besides the regex.
First your function block is not closed, you need to add another curly bracket at the end.
Here because you use ".value" Property you get a string with the actual email entered in the input field.
var email = document.getElementById("email").value;
But here you try to use the "email" variable as if it is the reference to the input object when it is in reality a string and does not have the ".value" Property.
if(email.value.match(emailPattern))
You should drop the .value and just use
if(email.match(emailPattern))
you make the same mistake in other places were you use the email variable.
Here is the corrected code with a naive regex for email matching.
function validate(){
const email = document.getElementById("email").value;
let error = "";
const emailPattern =/\w+#\w+\.\w+/;
if(email.match(emailPattern)){
console.log(`Your email ${email} is marvelous`);
return true;
}
else if(email == ""){
error = "You entered a blank email address. \n";
alert(error);
return false;
}
else {
error = "You have entered an invalid email address!";
alert(error);
return false;
}
}
<input id="email" type="text" value="">
<button onclick="validate()">Validate</button>
Related
I am trying to make an email validator and I want to make a command to check that the user input (the email the user enters) contains ONLY ONE OF "#" and ".". Example: name##.com would be invalid
function validateEmail(){
let enterEmail = prompt("Enter your email to see if it is valid");
let removeSpace = (enterEmail.trim());
let s = removeSpace.indexOf('#');
let lastS = removeSpace.lastIndexOf('.');
if (s > 1 && lastS > 1) {
Output("emailOutput", "The Email you have entered is valid");
}
else {
Output("emailOutput", "The Email you have entered is invalid");
}
}
I recognise this is not what you are asking (and may not be relevant) but in-browser validation of an email address is achievable via:
<input type="email" />
which degrades gracefully to
<input type="text" />
you can use:
const isEmailValid = (email) => {
const isValid = /\S+#\S+\.\S+/.test(email);
return isValid;
}
let s = "mail###.com"
s.match(/#/g).length
Length here will be the number of occurrences in the string
Maybe the subject line is incorrect, but here is my question:
I am trying to see if the user input is a valid email address, or if there is an input at all at the first place. if none of the above, then i want to loop the question requesting the answer again, until i get a valid answer(in this case, email address). Below is the code i have written, which was working until i added REGEX testing.
function emailPrompt() {
var ui = SpreadsheetApp.getUi();
var entry = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
var button = entry.getSelectedButton();
var response = entry.getResponseText();
var sum = 1;
for(var i=0;i<sum;i++){
var regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var matchRegex = regex.test(response);
if(response == ""||response == " "|| response != matchRegex) {
if(!matchRegex) { ui.alert("Invalid Email Address")}
ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
sum++;
} else {
sum--;
}
}
return response;
Logger.log(response);
}
Specifically, if the input is incorrect/invalid email address, i inserted another if statement to alert the user. I am positive i am messed the code somewhere in the REGEX matching/testing. Any help would be much appreciated. TIA
Your regex statement is ok. It tests and returns a boolean. Your first if statement is a little redundant. response == ""||response == " "|| response != matchRegex Most of these are already tested by the regex statement and the last one should never be false as you are comparing a string to a boolean.
EDIT: Additionally, the response variable is never update with the new prompt data (Code updated).
function emailPrompt() {
var ui = SpreadsheetApp.getUi();
var entry = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
var button = entry.getSelectedButton();
var response = entry.getResponseText();
var sum = 1;
for(var i=0;i<sum;i++){
var regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var matchRegex = regex.test(response);
if(!matchRegex) {
ui.alert("Invalid Email Address");
//Ask for email again and set new response.
var responseItem = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
response = responseItem.getResponseText();
sum++;
}
//sum--; this isn't needed to stop the loop.
if(sum > 3) //You shouldn't go on forever... Stop after a few tries?
break;
}
Logger.log(response); //Moved above return so this code runs.
return response;
}
I am currently having problems with displaying different span error messages for some of the same input texboxes based on if the user doesn't follow my validation rules. I really could use some suggestions of how I can make some of my if statements better to enforce my rules that I have setup. I am okay with how my if statement is validating the username and how if statement is validating the password, but I have been struggling to try to figure what is the best method for validating my repeatemail textbox and emailaddress textbox. Can someone help me? Thanks in advance! Here is my HTML, CSS, and JavaScript/JQuery code
$('#button2').on('click', function () {
var NewUsernameError = document.getElementById("New_Username_error");
var NewPasswordError = document.getElementById("New_Password_error");
var NewEmailAddressError = document.getElementById("New_Email_error");
// var NewRepeatEmailAddressError=document.getElementById("NewReenter_Email_error");
// How can I get my span id's to display one of two different error //messages based on my rules below? Right now it will only display first error //messages. Do I need to create two different span ids (except for the password // texbox) for each input textbox or is one span id fine how I currently have //it? Shouldn't I be able to display either message just using one span id?
if($(".newUsername").val().length < 6)
{
NewUsernameError.innerHTML= "The username must be at least 6 characters";
// NewUsernameError.innerHTML= "There is an already existing account with username";
}else
{
NewUsernameError2.innerHTML = '';
}
if($(".newPassword").val().length < 6) {
{
NewPasswordError.innerHTML= "The password must be at least 6 characters";
}else{
NewPasswordError.innerHTML = '';
}
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
{
NewEmailAddressError.innerHTML= "The email must not be left empty.";
NewEmailAddressError.innerHTML= "The email must contain # symbol in it.";
}else{
NewEmailAddressError.innerHTML= '';
}
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
}else{
NewRepeatEmailAddressError.innerHTML= '';
}
.
Lots of problems here.
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
That tries to compare the <input> element instead of its contents.
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
That tries to compare undefined instead of the form element's contents. (jQuery doesn't use .value.)
Instead, you want .val():
if($(".newEmail").val() == "" && $(".newEmail").val() != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
...
if($(".repeatEmail").val() != $(".newEmail").val() && $(".repeatEmail").val() == ""){
A secondary problem is where you try to assign two error messages simultaneously:
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
In these cases the second .innerHTML is going to immediately overwrite the first one, so the first error message will never be seen. Each of those errors needs to be in its own, separate if {} condition.
Third, this isn't how to do regex comparisons, that regex contains several syntax errors (no trailing slash, mismatched parens), and even if it worked it would disallow many valid email addresses:
$(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
Better email address validation regexes can be found in e.g. this question, but even those can disallow some valid addresses. Keep things simple and test only for what the error message claims you're testing for, the presence of an # symbol:
/#/.test($('.newEmail').val())
Putting it all together
Cleaning your original function, converting all the vanilla js into jQuery (there's no real drawback to mixing them other than that it makes the code harder to read, but I figure if you've already got jQuery may as well use it), and rearranging some logic to simplify the code results in this:
var validate=function() {
// clear out the error display ahead of time:
var newUsernameError = $("#New_Username_error").html('');
var newPasswordError = $("#New_Password_error").html('');
var newEmailAddressError = $("#New_Email_error").html('');
var newRepeatEmailAddressError = $("#Repeat_Email_error").html('');
// just to make the later conditions easier to read, let's grab all the values into vars:
var newUsername = $('.newUsername').val();
var newPassword = $('.newPassword').val();
var newEmail = $('.newEmail').val();
var repeatEmail = $('.repeatEmail').val();
// presumably you'll want to prevent form submit if there are errors, so let's track that:
var errorsFound = false;
if (newUsername === "") {
errorsFound = true;
newUsernameError.html("The username must not be empty.");
} else if (newUsername.length < 6) {
errorsFound = true;
newUsernameError.html("The username must be at least 6 characters.");
}
if (newPassword.length < 6) {
errorsFound = true;
newPasswordError.html("The password must be at least 6 characters.");
}
if (newEmail === "") {
errorsFound = true;
newEmailAddressError.html("The email must not be left empty.");
} else if (!/#/.test(newEmail)) {
errorsFound = true;
newEmailAddressError.html("The email must contain an # symbol.");
}
if (repeatEmail !== newEmail) {
errorsFound = true;
newRepeatEmailAddressError.html("This repeat email doesn't equal to the first one entered.");
}
// No need to test for repeatEmail being empty, since that's already covered by the newEmail case above.
// OK, all conditions checked, now:
if (errorsFound) {
// prevent form submit. (If this is called in an onsubmit handler, just return false.)
} else {
// allow form submit.
}
console.log("Errors found: ", errorsFound);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Username: <input class="newUsername">
<div id="New_Username_error"></div>
Password: <input class="newPassword">
<div id="New_Password_error"></div>
newEmail: <input class="newEmail">
<div id="New_Email_error"></div>
repeatEmail: <input class="repeatEmail">
<div id="Repeat_Email_error"></div>
</form>
<button onclick="validate()">Validate</button>
Keep one container for the errors you might expect to get on the input. I would do something like this to avoid all the else and else if's
$('#button2').on('click', function () {
// VALIDATE USERNAME
var newUserErrStr = '';
var newUsernameVal = $(".newUsername").val();
if(newUsernameVal.length < 6) newUserErrStr += "The username must be at least 6 characters";
document.getElementById("New_Username_error").innerHTML = newUserErrStr;
// VALIDATE PASSWORD
var newPasswordErrStr = '';
var newPasswordVal = $(".newPassword").val();
if(newPasswordVal.length < 6) newPasswordErrStr += "The password must be at least 6 characters";
document.getElementById("New_Password_error").innerHTML = newPasswordErrStr;
// VALIDATE EMAIL
var newEmailErrStr = '';
var newEmailVal = $(".newEmail").val();
if (newEmailVal === "") newEmailErrStr += "The email must not be left empty<br/>";
if (newEmailVal !== /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z]/ ) newEmailErrStr += "The email must contain # symbol in it.";
document.getElementById("New_Email_error").innerHTML = newEmailErrStr;
});
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-]+)*$
I've been searching this website for a tutorial on how to write a script that validates a form for four specific numbers. If the data is entered and does not match any of the four numbers, it should alert a 'Not Valid' message.
var input = document.getElementById("myInput");
var validNumbers = /^(123|777|989|111)$/;
var isFormValid = validNumbers.test(input.value);
if (!isFormValid)
{
alert("Not Valid");
}