JavaScript Form Validate - "False" not working as needed - javascript

I am trying to evaluate a form text/email field to see if there is something there and if so, run it past a regular expression valuation. It worked fine when I included the regex code in the SendEmail function with the rest of the logic but when I tried to move the regex part out into it's own function(validateEmailAddress), the validation still works but it doesn't seem to want to return false and just stop. Instead it continues on to the ajax part and sends the email regardless of whether it passes the regex test or not. It's the same code so I'm not sure why the "return false" doesn't work once the regex piece is moved out into it's own function.
Any thoughts are appreciated and THANK YOU!
function validateEmailAddress(address) {
filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!filter.test(address)) {
alert(address + ' - Is an invalid email address.');
return false;
}
}
function SendEmail() {
var emailFromVal = document.getElementById("EmailFrom").value;
var emailToVal = document.getElementById("EmailTo").value;
if (emailFromVal != 0) {
validateEmailAddress(emailFromVal);
} else {
alert("Please provide your email address.");
return false;
}
if (emailToVal != 0) {
}
else {
alert("Please provide your friend's email address.");
return false;
}
$.ajax({
method: 'POST',
url: '/_ajax/emailshare/',
dataType: 'json',
data: formCollection,
success: function (data) {
///send that email out
}
});
}

You are not doing anything with the return value from validateEmailAddress(), try this:
if (emailFromVal != 0) {
if(!validateEmailAddress(emailFromVal)){
return false;
}
} else {
alert("Please provide your email address.");
return false;
}
also, you need to return true from validateEmailAddress() when the email is valid:
function validateEmailAddress(address) {
filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!filter.test(address)) {
alert(address + ' - Is an invalid email address.');
return false;
}
return true;
}

return false; in validateEmailAddress will return just from validateEmailAddress, not from the enclosing function (SendEmail).
Your options are:
Check the return value of validateEmailAddress from the enclosing
function:
if(!validateEmailAddress(address)) return false;
OR
Throw from validateEmailAddress and catch the error from the
enclosing function (this'll allow the error to propagate up the
stack to an arbitrary length until you catch it--i.e., you don't
have to catch just from the enclosing function but also from its
caller or it's caller's caller, and so on and so forth).

Related

Attempting to solve jquery async issue

I am pretty new to javascript, and I am trying to work with mailgun's email validation feature and I am trying to get the validation to work (by ensuring the email data is intact prior to submission of a form.
https://github.com/mailgun/validator-demo
However I found that the function validation_success is always called asynchronously, resulting in the sequence as below:
checks start!
Feedback:390 checks complete! ErrorEmail=2
Feedback:347 execution begin
Feedback:404 validation begin! ErrorEmail=2
Feedback:419 validation complete! ErrorEmail=2
I want the sequence to be the following instead:
checks start!
validation begin! ErrorEmail=2 //this will update the ErrorEmail var.
validation complete! ErrorEmail=2
checks complete! ErrorEmail=2
execution begin
I have searched and tried all the techniques (async false/deferred/callbacks), but I can't seem to figure out what might have went wrong.
My code is as below:
var ErrorEmail = -1;
$(function () {
$('#User_Email').mailgun_validator({
api_key: 'x',
in_progress: validation_in_progress, // called when request is made to validator
success: validation_success, // called when validator has returned
error: validation_error, // called when an error reaching the validator has occured
});
$("#FeedbackForm").submit(function (event) {
if($("#User_Email").val())
{
check().done(function(){
console.log('execution begin');
if (ErrorEmail == 2) {
if (confirm('Are you sure this is the email you want to use?')) {
$(form).submit();
}
}
else if (ErrorEmail == 0)
{
$(form).submit();
}
});
event.preventDefault();
}
else
{
console.log('no email');
event.preventDefault();
}
});
});
function check(callback) {
var dfrd1 = $.Deferred();
console.log('checks start!');
dfrd1.resolve(
$('#User_Email').mailgun_validator({
api_key: 'x',
in_progress: validation_in_progress, // called when request is made to validator
success: validation_success, // called when validator has returned
error: validation_error, // called when an error reaching the validator has occured
}).done()
);
console.log('checks complete! ErrorEmail='+ErrorEmail);
return dfrd1.done().promise();
}
// while the lookup is performing
function validation_in_progress() {
$('#status').html("<img src=#Url.Content(#"~/Assets/img/loading.gif") height='16'/>");
}
// if email successfully validated
function validation_success(data) {
//var dfrd1 = $.Deferred();
//dfrd1.resolve(data);
console.log('validation begin! ErrorEmail=' + ErrorEmail);
$('#status').html(get_suggestion_str(data['is_valid'], data['did_you_mean']));
if (data['is_valid'] && !data['did_you_mean']) {
ErrorEmail = 0;
}
else if (data['is_valid'] && data['did_you_mean']) {
ErrorEmail = 2;
}
else
ErrorEmail = 1;
console.log('validation complete! ErrorEmail=' + ErrorEmail);
//return dfrd1.promise();
}
// if email is invalid
function validation_error(error_message) {
$('#status').html(error_message);
}
// suggest a valid email
function get_suggestion_str(is_valid, alternate) {
if (is_valid) {
ErrorEmail = 0;
var result = '<span class="success">Address is valid.</span>';
if (alternate) {
result += '<span class="warning"> (Though did you mean <em>' + alternate + '</em>?)</span>';
ErrorEmail = 2;
}
return result
} else if (alternate) {
ErrorEmail = 1;
return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
} else {
ErrorEmail = 1;
return '<span class="error">Email address is invalid. Please try another.</span>';
}
}
check() function already has a deferred object ($('#User_Email').mailgun_validator) the only thing to do is .pipe result of that function and call resolve function of dfrdl and in the end return dfrdl ONLY like below:
function check(callback) {
var dfrd1 = $.Deferred();
console.log('checks start!');
$('#User_Email').mailgun_validator({
api_key: 'x',
in_progress: validation_in_progress, // called when request is made to validator
success: validation_success, // called when validator has returned
error: validation_error, // called when an error reaching the validator has occured
}).pipe(function(res){
dfrd1.resolve(res);
})
console.log('checks complete! ErrorEmail='+ErrorEmail);
return dfrd1;
}

JQuery: Why is empty? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I'm creating a form and I want to validate it in real time. Everythings works in the ajax call, but I have a problem with the returns.
This is the code:
function checkEmail() {
var reg_exp = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
var mail = $("#email").val();
if (!reg_exp.test(mail) || (mail === "") || (mail === "undefined")) {
$("#mail_mess").html("Enter a valid email address");
return false;
}
else {
var r = '';
$.ajax({
type: "POST",
url: "index.php?p=jsform&ajaxcall=checkEmail",
data: {'mail':mail},
dataType: 'json',
success: function(res) {
r = res;
if(res) {
$("#mail_mess").html("OK");
//return true;
}
else {
$("#mail_mess").html("Email already Exists!");
//return false;
}
}
});
//alert(r);
return r;
}
}
$("#email").on("input", function() {
checkEmail();
});
$("#submitButton").click(function() {
if(... && checkEmail()) {
sendForm();
}
else {
$("#form_message").html("<span class='error'>All fields are required</span>");
}
});
As you can see, I call the function checkEmail() on input change (for the realtime validation) and on submit (all fields check before sending data).
The function checkEmail() should return false on invalid email or on already existing email and should return true on valid and non existing email.
Now.. the function works on realtime validation, I get the "non valid", "already exists" or "valid" exactly when I want. The problem is with the returns, because when I return r, it is an empty string (seems like r = res doesn't work).
And if I try to uncomment the returns inside the if(res)/else they don't work as well.
I'm sorry about my bad english! Thanks for any help :-)
checkMail should accept an optional callback, and call it with the result if defined
function checkEmail(callback) {
var reg_exp = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
var mail = $("#email").val();
if (!reg_exp.test(mail) || (mail === "") || (mail === "undefined")) {
$("#mail_mess").html("Enter a valid email address");
if(callback) {
callback(false);
}
}
else {
$.ajax({
type: "POST",
url: "index.php?p=jsform&ajaxcall=checkEmail",
data: {'mail':mail},
dataType: 'json',
success: function(res) {
if(res) {
$("#mail_mess").html("OK");
//return true;
}
else {
$("#mail_mess").html("Email already Exists!");
//return false;
}
if(callback) {
callback(res);
}
}
});
}
}
no need for callback function here
$("#email").on("input", function() {
checkEmail();
});
the fail function defined to avoid repetition because there's now two "false" paths
$("#submitButton").click(function() {
function fail() {
$("#form_message").html("<span class='error'>All fields are required</span>");
}
if(...) {
checkEmail(function(r) {
if (r) {
sendForm();
}
else {
fail()
});
else {
fail();
}
});

AJAX "success" executing before response is returned

I'm hoping this is just a simple fix due to me being a little dumb somewhere along the line. I'm executing my ASP.NET MVC login using AJAX. There is a "success" handler which returns a "true" value to the calling function which, in turn, load the home page.
The issue is that the "success" handler is executing BEFORE any value is returned - which means that nothing happens because the value is not "SUCCESS". I can confirm this by looking at the request in Firebug, the value returned is SUCCESS but nothing happens. If I apply a breakpoint to the end of the function and then continue execution it works just fine.
I have no idea what the issue is, I'd be very grateful for help or an explanation to what I'm doing wrong.
Thanks!
My JS Function:
function LogIn(UserName, Password) {
var Cont = true;
var ErrorString = "";
if (UserName == null || UserName == "") {
Cont = false;
ErrorString += "Username is Required.";
}
if (Password == null || Password == "") {
Cont = false;
ErrorString += "Password is Required.";
}
var result = false;
if (Cont) {
var LogInUrl = "/AJAX/LogIn?UserName=" + UserName + "&Password=" + Password;
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
result = true;
}
}
})
}
return result;
}
UPDATE: The function that calls the LogIn function:
$('#FormLogin').submit(function (e) {
e.preventDefault();
var UserName = $("#TxtLoginUsername").val();
var Password = $("#TxtLoginPassword").val();
var IsLoggedIn = LogIn(UserName, Password);
if (IsLoggedIn) {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
})
As I said, the function does it's job and logs me in, but the "success" handler seems to execute before the value is returned.
Change your ajax call to something like this:
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
}
});
There is no point in returning result from LogIn, it'll always be false. You need to put the code handling the returned value in the callback.
Another alternative, if you don't like the idea of your LogIn function being so closely coupled to DOM manipulation is to return the promise from your ajax call. So at the end of LogIn, you'd do something like this:
return $.ajax({
url: LogInUrl,
type:"GET"
}
});
And then when you call it, you'd do something like this:
LogIn(UserName, Password).then(function(data) {
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
});

Best code practice for javascript if-then-else

I'm looking for javascript and jquery experts to set me on the right path. I have the following code and I noticed that before the functions are completed the code passes through the focus() and return false; and again once the function comes back false; Will someone show me the proper way to write this code. Thanks!
// validate passwords
if(!VerifyPassword($("#CurrentPassword").val())) {
$("#CurrentPassword").focus();
return false;
}
if($("#NewPassword").val() != "") {
if(!ValidatePassword($("#NewPassword").val())) {
$("#NewPassword").focus();
return false;
}
if($("#NewPassword").val() != $("#RetypePassword").val()) {
alert("The new password is not the same as the retyped password");
return false;
}
}
function ValidatePassword(password) {
if(password.length < 6) {
alert("Password must contain at least six characters!");
return false;
}
re = /[0-9]/;
if(!re.test(password)) {
alert("Password must contain at least one number (0-9)!");
return false;
}
re = /[a-z]/;
if(!re.test(password)) {
alert("Password must contain at least one lowercase letter (a-z)!");
return false;
}
re = /[A-Z]/;
if(!re.test(password)) {
alert("Password must contain at least one uppercase letter (A-Z)!");
return false;
}
return true;
}
function VerifyPassword(password) {
urlString = "../sql/db_verify_password.php?Password=" + password;
/* send calendar updated information and return status message */
$.ajax({
type: "GET",
url: urlString,
dataType: "xml",
success: function(xml) {
$(xml).find('Results').each(function() {
var status = $(this).find('Status').text();
if(status != "OK") {
alert(status);
return false;
}
});
}
});
}
Let's see what happens in your code!
You first call
VerifyPassword($("#CurrentPassword").val())
which leads to
$.ajax({
//content omitted
});
Now, the first a in ajax stands for asynchronous. This means a request for some other resource will be made, but you won't wait until the request is finished (if you wait you would call it synchronous).
Instead, your code execution continues, setting the focus on the input and returning false.
Finally, when the request finishes and returns, then the function you specified in success: will be executed!
Knowing this you want to change the focus within the function specified in 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