Javascript - HAPPY.js password - javascript

i'm using happy.js to validate a form. for this form, i need the user to submit one of five possible passwords, if the user doesn't submit any of the passwords correctly the form has to fail.
not sure what i'm doing wrong here. appreciate any help. code below:
FRONT:
<script type="text/javascript">
$(document).ready(function () {
$('#form10').isHappy({
fields: {
// reference the field you're talking about, probably by `id`
// but you could certainly do $('[name=name]') as well.
'#Field226': {
required: true,
message: 'Please submit a valid Activation Code.',
test: happy.activationCode
}
}
});
});
</script>
HAPPY METHOD
var happy = {
activationCode: function (val) {
return (val == "dfgdfsg" || "uyioiuo" || "bvnm" || "zxvcx" || "z453v");
}
};

This will fix your problem...
return (val == "dfgdfsg" || val == "uyioiuo" || val == "bvnm" ||
val == "zxvcx" || val == "z453v");
You need to do the comparison of val == "something" for each of the values, which you weren't doing.
But I strongly urge you to reconsider this. Anyone can view your page source and will see all 5 passwords.

Your test function will always evaluate to true:
return (val == "dfgdfsg" || "uyioiuo" || "bvnm" || "zxvcx" || "z453v");
Because, you're doing OR with a string, and strings are truthy.
You need to change it to this:
return (
val == "dfgdfsg" ||
val == "uyioiuo" ||
val == "bvnm" ||
val == "zxvcx" ||
val == "z453v");
Of course, as others pointed out, this is completely insecure, so I hope you're just testing it and will have a more secure way of checking for passwords.

Related

Can you run part of an if statement conditionally?

Let's say I have this if statement:
if (
username === firstname &&
password !== fakePassword &&
givenname === lastname
) {
console.log(`Hi ${firstname}`)
}
Now I want to make the given name required if it's longer than 3 characters:
const givennameRequired = givenname.length > 3;
can I alter the if statement in a way that says "If the givennameRequired variable is true then worry about this part"
This way the console logs against two params or three depending on the validity of givennameRequired. Obviously I'm trying to avoid using an if/else and having two console logs
In a rough "sudo-code" way (I know this isn't valid):
if (
username === firstname &&
password !== fakePassword &&
(
if (givennameRequired) {
givenname === lastname
} else {
return true;
}
)
) {
console.log(`Hi ${firstname}`)
}
Basically, if the length is greater than three evaluate givenname === lastname otherwise, return true and don't worry about it.
This may do what you want:
if (
username === firstname &&
password !== fakePassword &&
(givenname.length <= 3 || givenname === lastname)
) {
console.log(`Hi ${firstname}`)
}
The if condition only bothers to check givenname === lastname if givenname.length > 3
This can be easily achieved with an if statement
if (givenname.length > 3){
//do something
}
else {
//do something else
}
Trying to keep in line with your syntax. Something like this should work. For your own sanity I'd consider nesting the if statements so you can provide more accurate feedback to the user.
if (username === firstname && password !== fakePassword && (givennamerequired == true && givenname === lastname && givenname.length() > 3))
) {
console.log(`Hi ${firstname}`)
}

using if statement with && and || inside for loop

I have an if statement inside for loop with more than one condition. I want to match the data in database with input data in an HTML form. When the input field in the form is blank it is stored as null in the database. I have this column(itemsSortedByDate[i].FD_MIMO) in the database which can be null or can have some value. I am unable to match the blank field with null in the database. Also even if that column(itemsSortedByDate[i].FD_MIMO) has some value in the database, my for loop searches for the database which has null field just because other fields are matching. My Javascript is as below. The last condition is creating problems. ScenarioListViewModel.fdMimo()and itemsSortedByDate[i].FD_MIMO are supposed to be same whether it's null or has some value. But in the console.log they are different. Thank you for your help, much appreciated.
self.getJobIdForCapacity = function(itemsSortedByDate){
var jobIdForCapacity;
var found = false;
for (var i = 0, len = itemsSortedByDate.length; i < len; i++) {
if(itemsSortedByDate[i].DB_Name == ScenarioListViewModel.db_name()
&& itemsSortedByDate[i].Split_Mode == ScenarioListViewModel.splitMode()
&& itemsSortedByDate[i].Full_Output == ScenarioListViewModel.fullOutput()
&& (itemsSortedByDate[i].Workflow_Status == "Completed" || itemsSortedByDate[i].Workflow_Status == "Running")
&& (itemsSortedByDate[i].Disposition == "Success" || itemsSortedByDate[i].Disposition == "None")
&& (itemsSortedByDate[i].FD_MIMO == ScenarioListViewModel.fdMimo() || itemsSortedByDate[i].FD_MIMO == null)){
jobIdForCapacity = itemsSortedByDate[i].Title;
console.log("Job Id:" + jobIdForCapacity);
console.log("fdmimo from form:" +ScenarioListViewModel.fdMimo());
console.log("fdmimo from list:" +itemsSortedByDate[i].FD_MIMO);
self.getJobResults(jobIdForCapacity);
found = true;
break;
}
}
if (!found) {
alert("Job not found in Sharepoint Execution History List. Click Execute Model to run");
}
};
I would suggest you use === in all the conditions in if statement and it may help you solve your problem as there is difference in === vs ==.
Please refer this question for the difference.
For example:
itemsSortedByDate[i].DB_Name == ScenarioListViewModel.db_name()
will be
itemsSortedByDate[i].DB_Name === ScenarioListViewModel.db_name()
Condition:
"Completed" || itemsSortedByDate[i].Workflow_Status == "Running"
will always return "Completed" does not matter itemsSortedByDate[i].Workflow_Status == "Running" is true or false. Here your can use ternary operator like
itemsSortedByDate[i].Workflow_Status == "Running"? "Running" : "Compelted"
Something of this kind. Check all conditions like this.

Does Javascript have a way to simplify multiple checks for a value to be one of?

I have this code:
if (tes.test.userTestStatusId != UserTestStatus.MarkedByAdmin &&
tes.test.userTestStatusId != UserTestStatus.MarkedByUser &&
tes.test.userTestStatusId != UserTestStatus.Paused &&
tes.test.userTestStatusId != UserTestStatus.Completed) {
Is there some way I could simplify this so as not to repeat "tes.test.userTestStatusId" each time?
If strict equality is OK, you can store the values as an array and use indexOf:
var statuses = [UserTestStatus.MarkedByAdmin, ...];
if (statuses.indexOf(userStatusId) === -1) {
//...
}
you can cache the value
var userId = tes.test.userTestStatusId;
if (userId != UserTestStatus.MarkedByAdmin &&
userId != UserTestStatus.MarkedByUser &&
userId != UserTestStatus.Paused &&
userId != UserTestStatus.Completed)
{
put the status in an array
var statuses = [ UserTestStatus.MarkedByAdmin, UserTestStatus.MarkedByUser, UserTestStatus.Paused, UserTestStatus.Completed];
now check the index
if ( statuses.indexOf( userId ) == -1 )
This won't be much less code, but it will be much more stable — you'll be able to add/remove cases from the status object without having to change the code.
The idea is to iterate through UserTestStatus properties and look for any that match:
if (!Object.keys(UserTestStatus).some(function(key) {
return UserTestStatus[key] == test.test.userTestStatusId;
})) {
// no matches found
}
Now if you come back and add a new case (maybe UserTestStatus.Failed or UserTestStatus.NotStarted) that code won't have to change.
You can use Array.some():
if (![
'MarkedByAdmin',
'MarkedByUser',
'Paused',
'Completed'
].some((p) => UserTestStatus[p] === tes.test.userTestStatusId)) {
// ...
}
But I personally think that the vanilla conditional approach is cleaner.
If I understand your question correctly, you can save the id in a new var and then use it in the if condition like below:
var statusId=tes.test.userTestStatusId;
if ( statusId!= UserTestStatus.MarkedByAdmin &&
statusId != UserTestStatus.MarkedByUser &&
statusId != UserTestStatus.Paused &&
statusId != UserTestStatus.Completed) {
But if you are looking for the way to combine multiple logical check in a single usage, it will not be effective as far as I know

How do you make a javascript "if" statement with both "and" and "or"?

I'm trying to make a page where you fill in some input boxes and check a radio button, and if you complete all of it, you can click a div, and animations happen. The specific input boxes are not the only ones on the page. I'm trying to use a javascript "if" statement that has a bunch of "and"'s and an "or" in parentheses, but when I open the page, the code doesn't run. This isn't all my code, and I know the javascript and it's libraries are linked because I've been coding this site for a while, and everything has worked up until now. I checked the code in a javascript validator and it seemed fine. I'm not sure what I'm doing wrong.
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== '' &&
$(".approvedBy").val() !== '' &&
$(".contractStartDate").val() !== '' &&
$(".proposalNumber").val() !== '' &&
$(!$("input[name='proposalReviewedForInvoice']:checked").val() || !$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
//do stuff
}
});
Alternatively I have
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== "" &&
$(".approvedBy").val() !== "" &&
$(".contractStartDate").val() !== "" &&
$(".proposalNumber").val() !== "" &&
$("input[name='proposalReviewedForInvoice']:checked").val() !== "" ) {
//do stuff
}
});
This code seems to work on another part of the site where there's only one input as a requirement.
Thank you if you can spot my error.
Wrap the || part in parentheses, otherwise the first operand to || is actually the last result from the last &&.
/*$*/(!$("input[name='proposalReviewedForInvoice']:checked").val() ||
!$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
And actually it seems that you rather had them wrapped in a $(), which will always return a jQuery object, which will always be "truthy" in the condition.
for handling errors much better if you only used the "OR (||) " condition.
$(document).ready(function(){
var management = $(".managementCompanyName").val();
var approved = $(".approvedBy").val();
var contract = $(".contractStartDate").val();
var proposed_num = $(".proposalNumber").val();
var proposed_rev = $("input[name='proposalReviewedForInvoice']:checked").val();
if ( management == '' || approved == '' || contract == '' || proposed_num == ''
|| proposed_rev == '' ) {
// error message
} else {
// do stuff
}
});

javascript null value not working

here's my function for checking zipcode. When a null values comes in, i keep getting "Object Required" Does anyone know where im going wrong?
aspx tags -
asp:CustomValidator
ID="cv_zipcode"
runat="server"
ControlToValidate="tb_zipcode"
ClientValidationFunction="ValidateZipcode"
ValidateEmptyText="true"
Display="Dynamic"
ValidationGroup="vgroup">
</asp:CustomValidator>
function ValidateZipcode(sender, args) {
var regZipcode = '\d{5}'
var zipcode = document.getElementById(sender.id.replace(/cv_/, "tb_"));
if ((zipcode.value == "ZipCode") || (zipcode.value.length == null) || (zipcode.value.length == "")) {
zipcode.style.backgroundColor = "#f6e086";
args.IsValid = false; return;
} else {
args.IsValid = true;
zipcode.style.backgroundColor = "white";
}
}
I'm not sure exactly which value is null, but in general, if you have a variable x which may or may not be null, and you want to do something with x, you can do the following:
x != null && do_something_with(x)
If x == null, then this returns false and doesn't try to execute do_something_with(). Otherwise, this expression returns the value of do_something_with(x).
If you just do_something_with(x), and x is null, and do_something_with() is not expecting a null, you can get errors.
EDIT:
try:
if ((zipcode == null) || (zipcode.value == null) || [everything else])
zipcode.value.length returns an integer
I think you should have
if ((zipcode.value == "ZipCode") || (zipcode.value.length == 0))
I would be a little suspect of this line:
if ((zipcode.value == "ZipCode") || (zipcode.value.length == null) || (zipcode.value.length == "")) {
Try this instead:
if ((zipCode.value == null) || (zipcode.value== "") || (zipcode.value.length == 0)) {
That error message usually indicates that you've tried to get or set a property or call a method of something that isn't an object, which tends to happen when a variable that you thought referred to an object is actuall null or undefined. That is, if someVariable is null or undefined then you can't say someVariable.someProperty.
If .getElementById() doesn't find a matching element it returns null, so in this line:
var zipcode = document.getElementById(sender.id.replace(/cv_/, "tb_"));
zipcode is potentially set to null, and if it is then all attempts to access properties of zipcode like zipcode.value and zipcode.style will fail.
If the parameter args comes in as null or undefined then attempting to set args.IsValid will fail, and similarly if the parameter sender is null or undefined then sender.id will fail.
So, if you have a variable that might be null you should test that before trying to do anything else with it.

Categories