Javascript: onSubmit function submits form before function has finished? - javascript

I'm asking this because I am at a complete loss myself and need a fresh pair of eyes.
The following JavaScript function is successfully called on submission of the connected HTML form. The function starts and the first two if statements run (and halt the submission if they return false).
Then, the first test alert "before" appears and then the form submits, completely missing out the rest of the function. While testing I changed the final line to return false so that whatever happen the function should return false, but the form still submitted.
function validateForm(form)
{
// declare variables linked to the form
var _isbn = auto.isbn.value;
var _idisplay = auto.isbn.title;
var _iref = "1234567890X";
// call empty string function
if (EmptyString(_isbn,_idisplay)==false) return false;
// call check against reference function
if (AgainstRef(_isbn,_iref,_idisplay)==false) return false;
// call check length function
alert("before");///test alert
////// FORM SUBMITS HERE?!? /////////////
if (AutoLength(_isbn)==false) return false;
alert("after");///test alert
// if all conditions have been met allow the form to be submitted
return true;
}
Edit: this is what AutoLength looks like:
function AutoLength(_isbn) {
if (_isbn.length == 13) {
return true; {
else {
if (_isbn.length == 10) {
return true; {
else {
alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
return false;
}
}

There are errors in your implementation of AutoLength. Currently, it looks like this:
function AutoLength(_isbn) {
if (_isbn.length == 13) {
return true; { // <------ incorrect brace
else {
if (_isbn.length == 10) {
return true; { // <------ incorrect brace
else {
alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
return false;
}
}
See how it doesn't close all of its blocks? That's because you've used the wrong brace in two places, and you've forgotten to close the function.
You could rewrite the function like this:
function AutoLength(_isbn) {
return _isbn.length === 13 || _isbn.length === 10;
}
If you're hell-bent on using alert, you can do that inside validateForm (although I would try to find a more user-friendly way to show the error message).
In the future, when you're trying to debug code, you can use try and catch to "catch" Errors as they happen, like this:
try {
if (false === AutoLength(_isbn)) {
return false;
}
} catch (e) {
alert('AutoLength threw an error: '+e.message);
}

If the execution of the function is terminated by a runtime error, the form submits. So check out the script console log for error messages.

Related

JavaScript form validation with else if

I have been creating JavaScript validation for a form though run into difficulties. There are currently two parts to parts at (at the moment) for JavaSCript to check (email and sms). THe script is only running email and not checking sms at all when should be checking both together. If both are fine then return true. Any ideas?
function validateForm() {
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
var errordiv = document.getElementById('error');
var errorsms = document.getElementById('errorsms');
/*postOptOutSix.checked = false;
postOptOutForever.checked = false*/
// Conditions
if (document.getElementById("emailradios") ==null && document.getElementById("emailforever") ==null) {
if (document.getElementById("smsforever") ==null && document.getElementById("smsforever") ==null) {
return true;
}
else if (document.getElementById("checksms").checked ==false && document.getElementById("smsOptOutSix").checked ==false && document.getElementById("smsOptOutForever").checked ==false) {
errordiv.innerHTML += "<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
else if (document.getElementById("checkemail").checked ==false && document.getElementById("emailOptOutSix").checked ==false && document.getElementById("emailOptOutForever").checked ==false) {
errorsms.innerHTML += "<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
You'd need to separate the 2 conditions checks, and only then check if some failed or not before returning.
Something like this should do the trick:
function validateForm () {
var errors = [];
// Empty any previous errors
document.getElementById('error').innerHTML = "";
// Check for SMS
if (!document.getElementById("checksms").checked &&
!document.getElementById("smsOptOutSix").checked &&
!document.getElementById("smsOptOutForever").checked) {
// add the SMS error to the array
errors.push("<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'");
}
// Check for Email
if (!document.getElementById("checkemail").checked &&
!document.getElementById("emailOptOutSix").checked &&
!document.getElementById("emailOptOutForever").checked) {
// add the Email error to the array
errors.push("<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'");
}
// Display the error(s) if any
if (errors.length > 0) {
errors.forEach(function (err) {
document.getElementById('error').innerHTML += err;
});
return false;
}
return true;
}
Also, I noticed that id='errorp' is there twice. Rename one of them.
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
You are setting the same variable from different elements. Shouldn't it be like this?
var emailBoxChecked = document.getElementById("checkemail").checked
var smsBoxChecked = document.getElementById("checksms").checked
Use HTML required and pattern attributes along with inputElement.checkValidity() which returns true or false. You could look on keyup, for example, to make sure all inputs are valid and if so enable the submit button and if not disable it.

How to check if eval returns nothing in JS

If I want to check if an eval function returns nothing, how do I do it?
I tried to do something like:
if (eval("iwuoinuvwoienvuwope") == "") {
// Do something
alert("Oh NO!");
}
But when I do like that nothing happends.
Here is my full code:
function calc() {
var cal = prompt("Your math....", "1 + 1");
if (cal == null) {
alert("If you don't have a math problem you can gtfo!");
} else if (cal == false) {
alert("If you don't have a math problem you can gtfo!");
}
/* Here I Check if eval is empty */
/* Here it doesn't work */
else if (eval(cal) == "") {
alert("Could you be more specific");
}
/* */
else {
alert("The answer is " + eval(cal));
}
}
<button onclick="calc();">Calculator</button>
eval(code) returns "the completion value of evaluating the given code. If the completion value is empty, undefined is returned." MDN
In your case, a valid math expression returns a Number. Thus you would have to check for typeof result == "Number". If you want to exclude NaN, Infinity and the like, perform additional checks e.g. by isFinite(result).
If you are trying to build a calculator, you should either be expecting a response, an exception or null.
try {
if (r === undefined) {
} else {
// handle response
}
} catch (error) {
// invalid
}
Validating whether it's a Number, and if the mathematical formula is valid will help you identity possible error outputs.

Validate forms using javascript

I want to validate 3 inputs (name, email and password) in a form using javascript. When the user submits the form, and all the fields are empty, it works correctly showing the error messages. But then if I write a correct password (length 7) and wrong email and name, and I try to submit the form again the "Password too short" message is stil there and the password is correct. What I am doing wrong?
Javascript file
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
function verPassword(){
var ok = true;
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
if(pass.length<6)
{
var text="Password too short";
document.getElementById('textPassword').innerHTML=text;
ok = false;
}
return ok;
}
HTML file
<form id='register' name='register' onsubmit="return verify()">
function verify(){
document.getElementById('textPassword').innerHTML = ' ';
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
change your code it like this:
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}
else
{
if(verName());
if(verEmail());
if(verPassword());
return false;
}
}
with this solution, each validation occurs if the previous validation runs true! and if not, just the previous validation errors shows up !
in each function verName(), verEmail() and verPassword(), return Boolean value of TRUE of FALSE
also add this line of code, on your form submit event:
verify() {
document.getElementById('textPassword').innerHTML= ' '
....
....
}
The problem is that your verPassword function is adding that error string when the password is invalid, but it doesn't remove it when the password is valid.
Also, your verify function makes little sense.
How about:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var ok = pass.length > 5;
var text = ok ? "" : "Password too short";
document.getElementById('textPassword').innerHTML=text;
return ok;
}
You have to empty the #textPassword element by write something like: document.getElementById('textPassword').innerHTML.
In addition I can see some wrong codes there. First, if every ver* function returns true or false, you better use && rather than & in if condition expression. Or you can just return the evaluated value of the condition expression like this: return verName() && verEmail() && verPassword().
Second, the ver* functions are already called while if evaluate condition expression. No need to call those functions again in else part.
And I don't think you need ok variable in verPassword() function.
I suggest to change the code like below:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var textPassword = document.getElementById('textPassword');
if (pass.length < 6) {
var text="Password too short";
textPassword.innerHTML = text;
return false;
} else {
textPassword.innerHTML = ""; // Empty #textPassword
return true;
}
}

Javascript IF blocks get skipped

I'm using this code to validate a form:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
if (isEmpty(name)) {
alert("3");
return false;
}
if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
if (isEmpty(city)) {
alert("6");
return false;
}
if (isEmpty(comments)) {
alert("7");
return false;
}
When hitting the "Submit" button, if the first two conditions do work(The ones that check if the email var is empty or not in email address format) - meaning that if I leave the email input empty or not in an email address format I get the alert (1 or 2).
The problem is that the rest of the validations get skipped and it doesn't matter if I leave another input empty or not in format.
Also, if I take the first IF block:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
And move it to the end of the validation block, everything works just fine.
I'm guessing I have a wrong syntax somewhere but I spent 2 hours looking and just couldn't find it.
P.S.
here are the two validation functions I'm using:
function isEmpty(field) {
if ((field == null || field == "")) {
return true;
}
return false;
}
function isEmail(field) {
var atpos = field.indexOf("#");
var dotpos = field.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
return false;
}
}
You use x.length in the isEmail function, but x is not defined.
the return statement exits the function to get all the validations run
keep all the validations in if else if blocks and keep on using return false every time.
or
set a variable to false whenever condition fails and then return the value. as j00lz said.
The
return false;
ends the function and stops the rest of the code being executed.
Instead set a variable:
result="false";
and at the end of the function add
return result;
What happens if you change it to this:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
else if (isEmpty(name)) {
alert("3");
return false;
}
else if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
else if (isEmpty(city)) {
alert("6");
return false;
}
else if (isEmpty(comments)) {
alert("7");
return false;
}
I'm just curious as to what happens if you make the whole thing one big if statement rather than breaking it up into parts, considering it's not going to change the validation process.
P.S.
I'm not sure if you realize or not, but with the way you have it set up, once one of the first if statements comes back false, returning false with in that if statement will end the whole method you're working in, meaning it won't run any other parts of it. So if you're shooting for displaying an alert for each and every empty input, etc, it won't happen this way.

Returning true or false from javascript function

I'm doing a regex check on a string within a function:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/,
matches = regex.exec(listOfZipCodes);
if (regex.exec(listOfZipCodes) === null) {
console.log('validation failed');
return false;
} else {
console.log('validation passed');
return true;
}
}
The regex is correctly detecting a valid/invalid list of zip codes.
I'm calling the function with this:
console.log('zip code: ' + listOfZipCodes);
if (ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
The problem is that the above if/else goes to the else clause, when the console output within the validation function shows "validation failed". So I must not be calling that function right.
What's the correct way to do what I'm trying to do?
Your function could be greatly simplified to:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
if (regex.test(listOfZipCodes)) {
console.log('validation passed');
return true;
} else {
console.log('validation failed');
return false;
}
}
...or:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
return regex.test(listOfZipCodes);
}
...or even just:
function ValidateZipCodeString(listOfZipCodes) {
return /^([, ]*\d{5})+[, ]*$/.test(listOfZipCodes);
}
...but the real issue (as Teemu points out) is not in your function, but in the use of it. Your function answers the question, "Is this a valid zip code string?", but your use of it is saying, "Say this is invalid if my function says it is."
Actually your validation function doesn't return true when validation fails. You just check the value incorrectly, it should be:
if (!ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
Others correctly pointed out that you just had your tests in the wrong order. However, and more importantly, your regex is incorrect, as it will for example return true for "1234567890".
Here is a suggestion:
function ValidateZipCodeString(listOfZipCodes) {
return /^\d{5}(\s*,\s*\d{5})*$/.test(listOfZipCodes);
}

Categories

Resources