I have a function that validates few different conditions. Here is the example of my function:
function checkData() {
var errorMsg = "",
fld1 = 0, //Number(document.getElementById('fld1').value),
fld2 = 5, //Number(document.getElementById('fld2').value),
fld3 = 1, //Number(document.getElementById('fld3').value),
fld4 = 0; //Number(document.getElementById('fld4').value);
if (!fld1) {
errorMsg += "Error 1\n\n";
}
if (fld1 === fld4) {
errorMsg += "Error 2\n\n";
}
if (fld2 > fld4) {
errorMsg += "Error 3\n\n";
}
if (fld3 > 3) {
errorMsg += "Error 4\n\n";
}
if (errorMsg !== "") {
var check = confirm(errorMsg + "\n Do you want to submit the form?");
if (check) {
return true;
} else {
return false;
}
}
return true;
}
<button onclick="checkData();">Click Here</button>
In the example above I hard coded some values for testing purpose. However, I'm wondering if I can refactor this code and find the better way of achieving the same result? Would ternary operators fit better? Or there is another way to get this to work? Thank you.
In this use-case I think the 'multiple-ifs' solution is quite clear so it is the one to use.
If you want to optimize a bit, I can only suggest
if(check){
return true;
}else{
return false;
}
to become
return !!check;
(the two exclamatives simply cast any object to a boolean vale :-))
The whole check variable is pointless. So return confirm is all that you need
function checkData() {
var errorMsg = "",
fld1 = 0, //Number(document.getElementById('fld1').value),
fld2 = 5,//Number(document.getElementById('fld2').value),
fld3 = 1,//Number(document.getElementById('fld3').value),
fld4 = 0;//Number(document.getElementById('fld4').value);
if(!fld1){
errorMsg += "Error 1\n\n";
}
if(fld1 === fld4){
errorMsg += "Error 2\n\n";
}
if(fld2 > fld4){
errorMsg += "Error 3\n\n";
}
if(fld3 > 3){
errorMsg += "Error 4\n\n";
}
return errorMsg !== "" ? confirm(errorMsg + "\n Do you want to submit the form?") : true
}
<button onclick="checkData();">Click Here</button>
You could refactor your if statements using the ternary operator. But chances are that it would make your code far harder to read. You could replace
if(check){
return true;
}else{
return false;
}
With just return check; as this is a boolean statement anyway.
Also, as far as readability goes it would be nice to label your field variables something more meaningful, as knowing that fld2 should always be greater than fld4 isn't immediately obvious from the name.
And if you don't care about highlighting the specific error codes then you could of course merge some of your checks together and just return false without the error codes specified, but I suspect you will want to keep that functionality.
Related
I just started to learn JS and I want to ask about a task that I could not complete.
var balance = 325.00;
var checkBalance = true;
var isActive = false;
//The first question
if (checkBalance = true) {
// the second question
if(isActive = false) {
console.log("Your account is no longer active.");
} else if(isActive = true) {
if(balance > 0) {
console.log("Your balance is " + balance.tofix(2) +"$.");
} else if(balance = 0) {
console.log("Your Accunt is empty");
} else {
console.log("Your balance is negetive, please contant bank");
}
}
else {
console.log("Thank you. Have a nice day");
The goal is to write an ATM and in order to do that I want to write more than one condition in the same time (as you can see in the code).
Why this code doesn't work?
Is it possible to write if statement inside another if statement?
Is there a better solution?
In javascript you should use === for condition equal
your code:
if (checkBalance = true) {
correct is:
if (checkBalance === true) {
same for
if(isActive = false) {
correct is:
if(isActive === false) {
= is assignment, == is used to check, change = to ==, === is used to check equality and type.
if (checkBalance = true) {
You are on the right track, it is indeed possible to write an if statement inside another one. But, you're missing a bracket and the way you check equality should be done differently. I edited your code so I can explain:
var balance = 325.00;
var checkBalance = true;
var isActive = false;
//The first question
if (checkBalance) {
// the second question
if(isActive = false) {
console.log("Your account is no longer active.");
} else if(isActive) {
if(balance > 0) {
console.log("Your balance is " + balance.tofix(2) +"$.");
} else if(balance === 0) {
console.log("Your Accunt is empty");
} else {
console.log("Your balance is negetive, please contant bank");
}
}
else {
console.log("Thank you. Have a nice day");
}
I mainly changed 2 things in your code. The first is changing
if (checkBalance = true)
Into this:
if (checkBalance)
Edit 1: Shorter if statements
You can omit the = true part because checkBalance is already a boolean value. This means that it is already true or false, which are values an if statement accepts. This brings me onto my second edit, which is the most important one.
Edit 2: Checking for equality
In your code, you use = true inside your if statements. Using only one = sign unfortunately is not checking for equality, but instead is your to assign values. You can only use one = when your assigning values like var a = 1;. Instead, you should use three = sings like ===. This actually checks two things. First, it checks if the type of values are the same. Then, it checks if the values are equal. You can also use two = sings like ==, this will check equality more loosely because it doesn't check if the types are the same. As noted in other answers, === is preferable here.
I hope this answers your question. If not, please comment below.
First one:
= : is assign
=== :is compare
One more thing wrong is :
balance.tofix(2)
It should be:
balance.toFixed(2)
and I just edited your code like this:
var balance = 325.00;
var checkBalance = true;
var isActive = false;
//The first question
if(!checkBalance) console.log("Thank you. Have a nice day");
else {
if(!isActive) console.log("Your account is no longer active.");
else{
if(balance > 0) {
console.log("Your balance is " + balance.toFixed(2) +"$.");
} else if(balance = 0) {
console.log("Your Accunt is empty");
} else {
console.log("Your balance is negetive, please contant bank");
}
}
}
You've been given good answers on the syntax errors. Regarding 'is there a better way', the need for equality checking of true and false using === is not necessary, because the true/false is already implied in the if condition. You can use it as the variable by itself. Also, since it is a boolean that can only be true or false, using if and then else is totally fine to do. No need to do if and else if.
Using a helper function to handle your complex case makes your code much more readable.
var balance = 325.00;
var checkBalance = true;
var isActive = false;
//The first question
if (checkBalance) {
// the second question
if(isActive) {
handleIsActive(balance);
} else {
console.log("Your account is no longer active.");
}
} else {
console.log("Thank you. Have a nice day");
}
function handleIsActive(balance) {
if(balance > 0) {
console.log("Your balance is " + balance.tofix(2) +"$.");
} else if(balance === 0) {
console.log("Your Accunt is empty");
} else {
console.log("Your balance is negetive, please contant bank");
}
return;
}
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.
I am having a problem with an if statement not recognizing a variables' value
The input is coming from a CSV file, saved to a variable and then passed into this function to check if it is true,
the checkusage console.logs are coming through with the value of "Y" but when ran it seems to keep skipping the checkusage if statement and executes the else statement.
VolumeChargeCalc = function(meterSize, checkusage){
console.log("Check usage value passed to function is = " + checkusage );
if(meterSize <= 20) {
console.log("METER SIZE HAS PASSED");
if(checkusage == "Y") {
console.log("Check usage has been found");
return [0.8042,0.8042,0.6879,0.6627];
} else {
console.log("no check usage found " + checkusage);
return [2.1442,0.8042,0.6879,0.6627];
}
} else if(meterSize == 999){
return [0.03035,0,0,0];
}
else {
return [0.8042, 0.8042, 0.6879, 0.6627];
}
}
I have tried a few different ways and the all have the same outcome, any ideas would be appreciated.
Thanks #mplungjan,
if (checkusage.trim() == "Y")
solved the problem, I guess the CSV was passing spaces through as well.
Not sure how to mark your comment as the answer sorry
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;
}
}
I created this function where it checks for multiple textboxes if they have values onsubmit. Basically it is a javascript form validator. When there are empty textboxes, form shouldn't submit and alert the user that there are required fields. Now, this works for me perfectly, however, when there are values already and the form is submitted, it still doesn't submit even though it should. I created an if statement to check if the errorString is empty or null, if it is, the form should submit but what happens is that it alerts the user with a blank string. I think the code is still going inside the if(errorString!=null || errorString=="") statement even though it shouldn't.
Thanks in advance
Please see my code below:
function validateForm()
{
var txtTitle = document.forms["actionStepsForm"]["txtTitle"].value;
var txtRequestor = document.forms["actionStepsForm"]["txtRequestor"].value;
var txtReprocessingRequest = document.forms["actionStepsForm"]["txtReprocessingRequest"].value;
document.getElementById('rowCount').value = counter-1;
var errorString = "";
if (txtTitle==null || txtTitle=="")
{
errorString += "Title field is required. \n";
}
if (txtRequestor==null || txtRequestor=="")
{
errorString += "Requestor field is required. \n";
}
if (txtReprocessingRequest==null || txtReprocessingRequest=="")
{
errorString += "Reprocessing request FR is required. \n";
}
if (errorString!=null || errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
}
//implementation if HTML form
<form name="actionStepsForm" id="actionStepsForm" action="add_reprocessing.php?action=add" method="POST" onsubmit="return validateForm()">
errorString can never be null because you've initialized it with "" so you can remove the condition "errorString != null".
It should become
if (errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
I think the correct condition should be
if (errorString != null && errorString != "")
otherwise the engine evaluated the 'errorString != null' condition, which evaluates to true (since errorString is "" and not null), and enter the code block.
Change
if (errorString!=null || errorString!="")
to
if (errorString!=null && errorString!="")
You have two 'not' statements that cancel each other out (one must always be false). Change it to:
if (errorString!=null && errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
The wrong line is the one everyone pointed out:
if (errorString!=null || errorString!="")
But I would like to point that you don't need to check for errorString!=null because you already created the variable as an empty string in the beginning of your code:
var errorString = ""; //created errorString as empty string
Therefore it will never actually be null, because you never set it as null anywhere (that is, you never set it as errorString = null).
If there are no errors, it will be an empty string always. So this will suffice:
if (errorString!="") //if errorString is different than what we created at `var`
{
alert(errorString);
return false;
}
else
{
return true;
}
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var errorString; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(errorString))) //this condition is important
{
alert("errorString"+errorString);
}
else
{
alert("errorStringis "+errorString);
}
}