JS email validation still submits invalid emails - javascript

I have a field where a user can submit multiple emails delimited by a comma character. I want JS validation to achieve two things:
If user tries to submit nothing, they get an alert that they have to enter an email, this WORKS
If user tries to submit any number of emails where one email is incorrectly formatted, they get an alert that one email has been improperly formatted, and they have to resubmit, this DOES NOT WORK
What happens with #2 is that if I submit something bogus like asddf as an email, I:
DO get the alert yay!
However, the form still gets submitted, BOO
Code:
$("#refer").click(function() {
var input_emails = $('#friend_emails').val();
if (input_emails === "") {
alert("Please enter at least one friend's email to send invites")
return false;
} else {
var parsed_emails = input_emails.split(',');
$.each(parsed_emails, function( index, email_value ) {
var trimmed_email = $.trim(email_value)
var atpos = trimmed_email.indexOf("#");
var dotpos = trimmed_email.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=trimmed_email.length) {
alert(trimmed_email + " " + "is not a valid email format, please correct and resubmit");
return false;
}
});
}
});

the return in your $.each(... is returning from the internal function. you need a way to return false from your outer function. something like this
$("#refer").click(function() {
var input_emails = $('#friend_emails').val();
if (input_emails === "") {
alert("Please enter at least one friend's email to send invites")
return false;
} else {
var success = true;
var parsed_emails = input_emails.split(',');
$.each(parsed_emails, function( index, email_value ) {
var trimmed_email = $.trim(email_value)
var atpos = trimmed_email.indexOf("#");
var dotpos = trimmed_email.lastIndexOf(".");
if (atpos< 1 || dotpos=trimmed_email.length) {
alert(trimmed_email + " " + "is not a valid email format, please correct and resubmit");
success = false;
}
});
return success;
}
});

Related

How to give alert message after all form validation is complete?

After the submit button for my form is clicked the function formvalidtion() is executed from a javascript file, below.
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
return FirstName(fname) && LastName(lname) && PhoneNumber(pnumber) && Email(email) && thankyou();
return false;
}
Example of individual validation.
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
As noted in the function formvalidtion() I have the function thankyou() referenced which is below.
function thankyou() {
if (formValidation() === true){
alert("Thank you for subscribing!");
}
}
The rest of the validation functions are working not this though, the acknowledgement alert is not appearing. TIA!
You send your function into a recursive pattern without a base case by allowing two functions call themselves(formValidation and thankYou). You can fix this by removing the conditional in the thankYou function
function thankyou() {
alert("Thank you for subscribing!");
}

if and else statements inside a while loop won't work

I'm trying to create an alert asking about the user email and if it's compatible to the stored variable, Then an alert will appear with Logged! message but the loop doesn't work with my code only if and else does but only for one time.
//working code
function validation(str) {
var str = prompt("Please Enter your email");
var email = "plapla#gmail.com";
if (str === email) {
return alert("Welcome back, Logged Successfully!" + " your email is " + str);
} else {
return alert("Your Email is incorrect, Please Try again");
}
}
validation();
//Loop Code
function validation(str) {
var str = prompt("Please Enter your email");
var email = "plapla#gmail.com";
while (str !== email) {
if (str === email) {
return alert("Welcome back, Logged Successfully!" + " your email is " + str);
} else {
return alert("Your Email is incorrect, Please Try again");
}
str++;
}
}
validation();
The variable str is not being updated in your loop. Your also using a return statement that will stop the loop after its first iteration.
You need to use prompt("") inside your loop and the condition to continue this loop is str !== email
If the message from the prompt is the same as the email, the loop will stop and code after the while will execute
var str = prompt("Please enter your email");
var email = "test";
while (str !== email) {
str = prompt("Please enter a valid email");
}
alert("Yeah ! Hello !");
I believe this is what you intended to achieve
function validation() {
var str = prompt("Please Enter your email");
var email = "plapla#gmail.com";
do {
if (str === email) {
alert("Welcome back, Logged Successfully!" + " your email is " + str);
} else {
str = prompt("Your Email is incorrect, Please Try again");
}
} while (str !== email)
}
validation();
You have to get the value each time you iterate, otherwise str isn't updated. To do so I used a do...while loop to execute it at least once, and loop while the user hasn't entered a correct value.
I removed str++ from your code since it doesn't mean anything to increment (++) a string value.
I changed a bit your concatenation inside the alert to something more concise.
I also removed the return statements because they would stop the execution of the function and it's not what you want.
function validation() {
do {
var str = prompt("Please enter your email");
var email = "plapla#gmail.com";
if (str === email) {
alert("Welcome back, Logged Successfully ! Your email is " + str);
} else {
alert("Your email is incorrect, please try again");
}
} while (str !== email)
}
validation();

Create multiple JavaScript variables?

I am new to JavaScript. Can someone please tell me what I am doing wrong? I have created an error message for an HTML form. The name field works, but I want to create an individual message if other fields are left blank.
Below is my JavaScript code:
function validateForm() {
var name = document.forms["contactform"]["name"].value;
if (name == "")
var email = document.forms["contactform"]["email"].value;
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
return false;
document.getElementById('erroremail').innerHTML = "Please enter your email";
return false;
}
}
Syntactically:
This code is not reached: document.getElementById('erroremail').innerHTML = "Please enter your email";
Put it before the first return and remove the second return.
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
document.getElementById('erroremail').innerHTML = "Please enter your email";
return false;
}
Logically:
Why would you test twice the same exact thing?
Solution:
Test for empty email => do something
Test for empty name => do something
The problem in your code is that you return something before checking another validation. When you return something, the function stops and nothing after return gets validated.
In your situation,you can declare a variable which is true by default var ret=true; and if a condition doesn't meet your requirements it becomes false.
For example:
function test() {
var ret = true;
if( 1 !== 1 ) {
ret = false; //you will return false in the end
}
return ret; //return the result. from this point on, the function exits and doesn't do anything after
alert("This will not be executed because there is a 'return' before");
}
The above function will return false and it will not execute the alert because you already return a result from that function
What you need is:
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
ret = false;
}
var email = document.forms["contactform"]["email"].value;
if (email== "") {
document.getElementById('erroremail').innerHTML = "Please enter your email";
ret = false;
}
return ret;
}

If statements not initialising JavaScript

Here is my code for a simple HTML form with JavaScript Validation. I simply want to return an error message if the fields are blank.
At the moment the page just goes straight to the success.html page without initialising the javascript. Any help would be greatly appreciated!
Ok so I've made some changes and its still not working. Here is the edited code:
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value==="") {
msg+="You must enter your name \n";
document.ExamEntry.Name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value==="") {
msg+="You must enter the subject \n";
document.ExamEntry.Subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if(msg===""){
return result;
}else{
alert(msg)
return result;
Thanks for all the contributions
The curly parentheses surrounding the logic following the below if statement are invalid
if (msg !== "") {
return result;
} {
alert(msg)
return result;
}
Simply, you should write:
if (msg !== "") {
return result;
}
alert(msg);
return result;
Am I reading this wrong or are your if statement logic backwards?
if (document.ExamEntry.name.value !== "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value !== "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
result by default is true. If you fail to enter a value for either fields, then !== "" will be false (because it does equal the empty string) and therefore result will be left true, which enables form submission.
Try:
if (document.ExamEntry.name.value === "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value === "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
Also, as others pointed out, you are missing an else statement:
if (msg !== "") {
return result;
} else {
alert(msg)
return result;
}
And finally, you mentioned this is Java. This is JavaScript. And no, JavaScript is not just a smaller version of Java. It is a very different language.
It looks like you are comparing with non-empty string while the comparision should have been for an empty string i.e.,if (document.ExamEntry.name.value !== "") { should be changed to if (document.ExamEntry.name.value == "") {
This implies to check for a a non empty string in the text box and redirect to the appropriate page (success page).
Also move the alert(msg) to the if (msg !== "") block. I think you would want to alert the user in case of empty text box.

Javascript / Ajax / PHP - Small issue driving me nuts

I need some guidance, as im literally going crazy here.
Ive created code with php/js/ajax to check if email address exist when submitting.
So ive tested the ajax and the correct values are being returned. (checked via firebug)
Either 1 for user exists
or 2 for user doe not exist.
Now ive added an alert box to check the value and for some strange reason it always displays value 1!
(even though ajax value is 2)
function validateForm() {
var x3=document.forms["newuser"]["email"].value;
//Check if username exists.
$.post(
"http://...check_user_exists.php",
{
x3 : x3 //user email
},
function(data) {
email_check = parseInt((data.email_exists),10);
}
);
//Additional Checks
if (email_check = 1) {
$("#form_status").fadeIn("slow");
$("#form_status").text("Email Address Taken.");
alert(email_check);
return false;
}
if (email_check = 2) {
$("#form_status").fadeIn("slow");
$("#form_status").text("Email ok.");
alert(email_check);
return true;
}
more validation checks....
Hi all, and again... thank you for your kind guidance.
Firstly, I would like to apologize as i'm quite new to this...
I've moved forward slightly but stuck on the last part and not sure how to proceed.
So the form now validates the form elements and checks the email to see if it exists.
The only issue I have left is if the email value is ok, the form does not process.
Is there a way to set submit value to true with the ajax callback function?
<form name="newuser" id="form" method="post" action="do_new_user.php" onsubmit="return validateForm()">
function validateForm()
{
var x=document.forms["newuser"]["name"].value;
var x2=document.forms["newuser"]["surname"].value;
var x3=document.forms["newuser"]["email"].value;
var x4=document.forms["newuser"]["password1"].value;
var x5=document.forms["newuser"]["password2"].value;
if (x==null || x=="")
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Please enter your name.");
return false;
}
//more validation.....
//Check if username exists.
$.post("http://ryangosden.com/breadcrumbs/check_user_exists.php",
{
x3 : x3
} ,
function(data)
{
var obj = jQuery.parseJSON(data);
if (obj.email_exists == 1)
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Email Address Taken.");
}
if (obj.email_exists == 2)
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Email ok.");
validateForm(true);
}
});
return false;
}
Thanks again all.
You are not comparing but assigning 1 to email_check
if (email_check = 1)
but should be
if (email_check == 1)
= is an assignment operator
== is a comparison operator
=== is a strict comparison operator
why you are assigning the value instead of comparing it.
= assigns the value
== compares the value
if (email_check = 1)
you should do this:
if (email_check == 1)
and
if (email_check == 2)
The callback function is called asynchronously. Therefore you cannot call validateForm() in the way that you are expecting to, which contacts the server, parses the result, and returns true or false. What actually happens is that the $post( ... code runs, but does not wait for the response. Instead, it immediately continues through the code if (email_check = 1) { ... (which should have a == instead of =) without waiting for the POST response. Only later when the response is received is email_check actually set via the callback function, but the remainder of validateForm() has already completed.
Instead, whatever you intend to do with the return value, you must do in the callback function itself. That is, replace
function(data)
{
email_check = parseInt((data.email_exists),10);
});
with
function(data)
{
email_check = parseInt((data.email_exists),10);
alert("In callback: email_check = "+email_check);
if (email_check == 1) {
$("#form_status").fadeIn("slow");
$("#form_status").text("Email Address Taken.");
}
if (email_check == 2) {
$("#form_status").fadeIn("slow");
$("#form_status").text("Email ok.");
}
});
Anything else you were doing with the return value of validateForm() should also go in the callback function.

Categories