If, Or, while Not.... Javascript help needed - javascript

Hi folks I was curious if someone could help me out. I don't usually post on here but I have exhausted all my efforts and can't figure this out. I have this code here
function insertVideo(link)
{
if (link)
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
var editpane = document.frmPost.addesc;
var linkcode = "[EMBED]" + link + "[/EMBED]";
editpane.focus();
/*if (document.selection)
{
document.selection.createRange().text = linkcode;
}
else*/
if (editpane.selectionStart || editpane.selectionStart == '0')
{
var selstart = editpane.selectionStart;
var selend = editpane.selectionEnd;
editpane.value = editpane.value.substring(0, selstart) + linkcode + editpane.value.substring(selend);
editpane.selectionStart = selstart + linkcode.length;
editpane.selectionEnd = editpane.selectionStart;
}
else
{
editpane.value = editpane.value + linkcode;
}
editpane.focus();
}
}
The problem I am having is when the user trys top post a youtube video with https in the address.
I understand that if I change
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
to
{
if(link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
It works. But then when the user enters the http address without the https it no longer works. I figured I could combine the statement with an OR, but this doesnt work either, I had
if(link.substring(0,29)!="http://www.youtube.com/watch?" || link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
So basically I need it to work in both situations (https and http) not just one or the other.
I am stumped, Im no pro with javascript so I sure its a minor error but I have spent far too much time trying to figure this out on my own. Please help if you can. Thanks!

It's as simple as changing the OR (||) to an boolean AND (&&).
if (link.substring(0,29) !== "http://www.youtube.com/watch?" && link.substring(0,30) !== "https://www.youtube.com/watch?") {
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
// the else is unnecessary
// else {
link = link.replace(/watch\?/,"").replace(/\=/,"/");
// }
This works as in your original code, if your URL is http://, it will fail the https:// check (or vice versa), making the conditional true, therefore running your failure code. Changing it to && fixes it as the URL is now required to fail both tests to be invalid.
Just a little note: unless you're doing it deliberately (or in other special circumstances), you should use the === and !== forms of equality testing (instead of == and !=), as these fail automatically if they are of different types instead of converting the types implicitly.

Related

How to turn this Password validation right?

var password=123;
var input;
var opp=0;
for(var t=0;t<=2;t++){
if(password!=input && t<=2){
input=prompt("enter your password");
}
else{
opp++;
}
}
if(opp!=0){
alert("success");
}
else if(opp<1){
alert("fail");
}
im expect it to be a password validation which can only try three times.
but it will failed even with typing correct password in the third try.
Let's begin saying this should just be a didactic excercise.
I suggest you to drop the for loop strategy and embed the logic inside a while loop that will keep running as long as the attempt counter variable will be <=3.
Until the typed password still doesn't match the expected one, it will keep asking for a new password after saying fail for a total amount of 3 attemps max.
If the typed password matched, it just alerts the user saying success and exiting the loop.
Of course as just said by other users, this approach is very wrong in terms of security starting from the fact that the expected password is stored in plain text.
As a side note, the expected password defined as a literal should be a string literal and not a number.
let password = '123';
let attempt = 0;
let input;
let wasSuccess = false;
while(++attempt<=3){
input = prompt("enter your password");
if(input == password){
wasSuccess = true;
alert('success');
break;
}else{
alert('fail');
}
}
if(wasSuccess){
//perform any logic expected to run after successfully logged in
}
I am not sure what it is you are trying to do, this is totally unsafe.
To easily crack your password challenge, click 'view source' on the browser, and lookup the password.
Please use better authentication, preferably on the server, not in javascript.
Of course you can use Javascript, but not for actual password checking.
Since OP is just trying and will never use this in a production environment, here is a working piece of script:
var password= "123";
var input;
var tries=1;
var maxTries = 5;
var passed = false;
while ( (!passed) && (tries <= maxTries) ){
input=prompt("enter your password (attempt nr "+tries+")");
if (input === password){
passed = true; // Yeah!
} else {
tries = tries + 1;
}
}
if (passed){
alert("success");
} else {
alert("fail");
}

Javascript - More than one condition

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

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.

jQuery - Checking val isn't empty and contains a specific piece of text

So I've got a .js file that checks that the values of my form. I'm trying to check that the form values aren't empty, and that one of the values contains a specific piece of text (in this case, my name). If the form does hold my name, then run the rest of the script.
Where I have commented //etc etc, an AJAX script is ran that posts to a PHP file.
This is all functioning as expected, until I run the additional if statement checking the input value for my name.
$('#submit').click(function(e){
this.enabled=true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === ""){
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if($('#name').val().indexOf("Rich") != -1){ // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
// etc etc
});
Question: How would I go about checking that the value of the id '#name' isn't empty, and that it contains a specific piece of text?
Thanks in advance,
Richie.
Solution:
I removed the additional if statement and included the following code.
var name = $('#name').val();
if ( name.indexOf("Rich") || $.trim($("#name").val()) === ""){
If you indent your code consistently, it's fairly clear why you have a problem:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if ($('#name').val().indexOf("Rich") != -1) { // Note that this is WITHIN the `if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "")` condition
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
If you want it to be handled, it needs to be an else if for that condition instead:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
} else if ($('#name').val().indexOf("Rich") != -1) { // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
(Well, as you have return, those could both just be if rather than else if...)
There are other problems though, for instance this expression in your final block:
$('#name, #topic_title').length
...which checks to see if either #name or #topic_title elements exist in your DOM at all (it doesn't do anything to check their values, and it doesn't require that they both exist, just one of them), and this:
$('#name, #topic_title').val().length
...will only check the value in #name, it will completely ignore the value in #topic_title, because when used as a getter, val only gets the value of the first element in the jQuery set. (Almost all of jQuery's functions that can be getters or setters are like that; the exception is text which is different from the others.)
Finally, this line:
this.enabled = true;
...is almost certainly a no-op, since the button cannot be clicked if it's not enabled, and as lshettyl points out, the property's name is disabled, not enabled. So this.disabled = false; if you're trying to enable it, or this.disabled = true; if you're trying to disable it.
By the look of your code, I assume you have a form that has either a class or an ID (or nothing). It'd be clever to use the form's submit event as opposed to click event of the submit button. This way you ensure that the form can also be submitted via the enter button (remember accessibility?). This is only an extension to T.J. Crowder's answer which has lots of good points from which you can learn/improve coding.
//Let's say your form has an ID 'topic'
$("#topic").on("submit", function() {
//Cache jQuery objects that would be resued, for better performance.
var $name = $("#name"),
$title = $("#topic_title"),
$msg = $('#message');
//One of the elements doesn't exist (exit)
//1 + 1 <= 1
if ($name.length + $title.length <= 1) {
return;
}
if ($.trim($name.val()) === "" || $.trim($title.val()) === "") {
$msg.html('you did not fill out one of the fields').css("color", "#be4343")
return;
} else if ($name.val().indexOf("Rich") !== -1) {
$msg.html("You have entered the wrong name.");
return;
} else {
//You do not need further checks such as length, val etc.
//as they have already been checked above.
var name = $name.val();
var topic_title = $title.val();
}
});
You can make comparison to know if it's empty:
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
if(name=='' || name==undefined){
//do stuff here
}
});

Strange GET Data Causing 404 Error - JavaScript Form Validation

I want to refer to this post, because it might relate:
Make Form Fields Optional with JavaScript Validation
I have a form with three optional fields, as described above. If I click the submit button, the JavaScript alerts come up, but the last one is a URL instead of the string I specify in the JavaScript function (the one that isn't an alert strong but an URL).
After a second, the page tries to go to an invalid URL:
localhost.../index.php/Don%27t%20forget%20the%20location.
As it turns out the Don%27t%20forget%20the%20location. is the alert string I have in the JavaScript function.
I thought that I might have some weird code that I accidentally pasted somewhere causing this but I scoured my files and found nothing out of the ordinary that would cause this. Not sure if this is a bug or something I'm doing wrong.
EDIT
I have JavaScript form validation functions like so:
function validate_name(field)
{
if (field == "") return "Please enter the name.\n";
return "";
}
function validate_specialty(field)
{
if (field == "") return "Please enter the specialty.\n";
return "";
}
function validate_location(field)
{
if (field == "") return "Don't forget the location.\n";
return "";
}
where the function that is called from the form's onSubmit is:
function validate_form(form)
{
name = validate_name(form.name.value);
specialty = validate_specialty(form.specialty.value);
location = validate_location(form.location.value);
if (name == "" || specialty == "" || location == "")
{
return true;
}
else
{
alert("You must enter at least one field:\n\n" + name + specialty + location);
return false;
}
}
It's because the variable location refers to window.location in that case (the url). So if you change your variable name, that should work:
userLocation = validate_location(form.location.value);
and
alert("You must enter at least one field:\n\n" + name + specialty + userLocation);

Categories

Resources