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

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!");
}

Related

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

My function works just once

I have a problem with my function. I want to make a login form validation by JSON data. My code works fine, but only when I put correct data just after refresh. For example, when I enter incorrect login/password I receive error, but after that when I type correct login/password nothing happens.
I'll be very grateful if you can help. Here is my js code:
//JSON validation
function validation(username, password){
var alert = document.getElementById("invalid-data");
data = JSON.parse(data);
for (var i=0; i < data.length; i++) {
if (username == data[i].login && password == data[i].password) {
window.open("panel.html", "_self");
} else {
alert.style.display = "block";
}
}
}
//Form validation
function getLoginInfo() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
validation(username, password);
}
var button = document.getElementById("login-button");
button.addEventListener("click", getLoginInfo);
i hope your problem is data = JSON.parse(data); because when first time you get parse data you put it into data again and it cause problem in your next data json parsing. so i think your problem would be solve if you put your parsed data into different variable like code bellow:
//JSON validation
function validation(username, password){
var alert = document.getElementById("invalid-data");
var parsed_data = JSON.parse(data);
for (var i=0; i < parsed_data.length; i++) {
if (username == parsed_data[i].login && password == parsed_data[i].password) {
window.open("panel.html", "_self");
} else {
alert.style.display = "block";
}
}
}
//Form validation
function getLoginInfo() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
validation(username, password);
}
var button = document.getElementById("login-button");
button.addEventListener("click", getLoginInfo);
So, problem of this function was that
data = JSON.parse(data);
was inside a function. I made it global and everything works fine.

Javascript convert alert to string

I have this small javascript to validate form input.
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
I'm tryin to figure out how to get the "alert" message as a string to show it later on the page instead of popping this ridiculous box. Looks simple to me but i'm a big zero in js. Any help appreciated, Thanks !
The alert() method is what makes the big pop up box. If you want to save the value for later use save it to a variable. Something like:
var message = "";
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
message = "Some fields need correction:\n" + reason;
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
var alerter;
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
alerter = "Some fields need correction:<br/>" + reason;
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
document.body.innerHTML = alerter;
How about assigning the string to a property of "window" :
window.myAlert ="Some fields need correction:\n" + reason);
Then you can get it from anywhere:
document.body.innerHTML = window.myAlert;

JS email validation still submits invalid emails

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

Javascript If statement evaluation not working correctly [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
So this is my code for some ajax that I'm doing.
function check_password(){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
},
function(response) {
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
return response.indexOf('success');
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
and here I'm trying to handle the return value from the check password function.
jQuery(function() {
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
} else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
} else if (check_password() != 73) {
hasError = true;
$("#password").after(check_password());
}
if (hasError == true) {
return false;
}
});
});
For some reason the if statement is returning true even when the index(return value) is 73. I test this by using jquery within the if statement to print out the value of the returning function and it prints out 73. I have a feeling my error is caused because of dynamically typed variables in javascript.
Typical asynchronous behavior issue of AJAX calls. You return response.indexOf('success'); from your AJAX callback, but since it is an asynchronous callback, there is nothing to return to. The rest of you check_password function has long finished when the callback is being called.
To fix this you need to completely restructure your code. In your click handler, you first need to call your post() function and then in the callback you need to go through your if/else if blocks.
Your function ´checkpassword()´ doesn't actually return a value.
It launches a request to a PHP-file and immediately returns (without a value).
You do specify a callback for when the call returns, but that never gets back to your original function.
You could do something like this:
function check_password(callback){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
callback(response.indexOf('success'));
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
jQuery(function(){
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
}
else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
}
else (
check_password(function(returnValue) {
if (returnValue != 73) {
hasError = true;
$("#password").after(check_password());
}
})){
}
if(hasError == true) {return false;}
});
});
Of course, this code just shows you how to get the value inside the other function, but you still need to handle the fact that you're other function doesn't return immediately and that for example the value of HasError is not set immediately.
Your problem is that you return from within a inner function, which will never ever work in JavaScript. Pass a callback:
function check_password(callback) {
// ...
callback(response.indexOf('success'));
}
// ...
check_password(function(result) {
if(result != 73) {
// ...
}
})
Just search for JavaScript AJAX and you will find a lot of sites to study. Here is one of them: http://www.html5rocks.com/en/tutorials/async/deferred/

Categories