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}`)
}
Related
I would like to be able to skip checking a variable if the property (.emailAddress) has the chance of being undefined but continue checking the others.
For example, I'm checking an entered email address if its an existing contact (email) on the page.
if(inputEmail.length > 0 && inputEmail.indexOf('#') > 0 */ check that the input is not blank & is probably an email address.
&& inputEmail !== existingContact1.emailAddress
&& inputEmail !== existingContact2.emailAddress
&& inputEmail !== existingContact3.emailAddress
&& inputEmail !== existingContact3.emailAddress
) {
// execute code
}
My problem occurs if .emailAddress is undefined, as you can't check undefined in an If statement.
.emailAddress could be any combination of existingContact 1-4 that could be undefined or not.
can’t check should read can’t compare undefined.
I've tried using typeof to find if it is undeclared with not the results I was expecting.
&& typeof existingContact1 == "undefined" || typeof existingContact1.emailAddress == "undefined" && existingContact1.emailAddress !== inputEmail
What are some diffrent approaches to be able to anticpte and skip over if .emailAddress has the chance of being undefined?
In programming undefined & null evaluate/return to false, so check like this
if(inputEmail && inputEmail.indexOf('#') > 0 */ check that the input is not blank & is probably an email address.
&& inputEmail !== existingContact1.emailAddress
&& inputEmail !== existingContact2.emailAddress
&& inputEmail !== existingContact3.emailAddress
&& inputEmail !== existingContact3.emailAddress
) {
// execute code
}
try the approach like
var existingContact1 = { emailAddress: 'abc#zyz.com' }
var existingContact2 = { emailAddress: 'abc#zyz.com' }
var existingContact3 = { emailAddress: 'abc#zyz.com' }
var existingContact4 = { emailAddress: 'abc#zyz.com' }
if(inputEmail.length > 0 && inputEmail.indexOf('#') > 0 */ check that the input is not blank & is probably an email address.
&& [existingContact1, existingContact2, existingContact3, existingContact4]
.map(({ emailAddress }) => emailAddress) // get existing emails
.filter(x => x) // remove falsy values if any
.indexOf(inputEmail) > -1 // check if available
) {
// execute code
}
The wonderful thing about javascript is you can work with undefined. I highly recommend keeping everything as simple as possible at all times. Let's cover some cases:
You can literally assess with === operator if something is undefined. === returns true when the values on both sides are equal in value and type, which is how you'd check if a value is not defined in the most explicit way.
You can use a lazy falsy check, which is actually what I recommend. Using !!x (or just x in an If statement) will coerce it to boolean, and it will return true if x is a non-empty string and is not undefined.
I want to add as a footnote that I would recommend just keeping an array called emailsOnPage and then checking if input.email is in the array, rather than manually checking 4 conditions.
Robin mentioned the case insensivity of emails, and that's easy to do; just use the form if(x.toLowerCase() == y.toLowerCase()).
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.
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.
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
}
});
AddPatient = {};
AddPatient.Firstname = FirstNameValue || PatientModel.errorMsg('FirstName',FirstNameValue);
AddPatient.LastName = LastNameValue || PatientModel.errorMsg('LastName',LastNameValue);
AddPatient is an Object and i am checking it whether its blank or not before sending the request.
PatientModel.js
errorMsg: function(title,FirstNameValue,LastNameValue) {
if(FirstNameValue === undefined || FirstNameValue === ' ' && LastNameValue === undefined || LastNameValue = ' ') {
alert('FirstName and LastName are missing');
return false;
} else {
alert(+title 'is missing');
return false;
}
}
I have a form, where i have FirstName and LastName field and i have to check it should not be blank. I want a single function in javascript which can work.
Is this the right way to do it?
I can see a couple of problems in your code.
Mismatch between errorMsg()'s expected arguments and how it is called
Syntax error in second alert()
Bad expression inside if statement
Mismatch between errorMsg()'s expected arguments and how it is called
Your errorMsg() function expects three arguments, but you only pass it two at a time:
errorMsg: function(title,FirstNameValue,LastNameValue) {
....
}
... and then ....
.errorMsg('FirstName',FirstNameValue);
.errorMsg('FirstName',LastNameValue);
If you really want to use both values inside errorMsg(), you need to pass them both every time, in the same order the function expects them:
PatientModel.errorMsg('FirstName',FirstNameValue,LastNameValue);
PatientModel.errorMsg('LastName',FirstNameValue,LastNameValue);
// This is weird code, but it'll work
Syntax error in second alert()
This is simple enough to fix, and could have been just a typo.
alert(+title 'is missing');
^ ^_There's something missing here.
|_This will only try to convert title to a number
What you want is this:
alert(title + 'is missing');
Bad expression inside if statement
if(FirstNameValue === undefined || FirstNameValue === ' ' && LastNameValue === undefined || LastNameValue = ' ') {
This won't work as you expect, because && has greater precedence than ||, meaning the expression will be evaluated as such:
if (
FirstNameValue === undefined
|| (FirstNameValue === ' ' && LastNameValue === undefined)
|| LastNameValue = ' '
) {
You would need parenthesis to fix the precedence:
if( (FirstNameValue === undefined || FirstNameValue === ' ') && (LastNameValue === undefined || LastNameValue = ' ') ) {
This is irrelevant, actually, because the expression can be simplified like this:
// If these values are taken from a form input, they are guaranteed to be strings.
if(FirstNameValue.length === 0 && LastNameValue.length === 0) {
Or even better, like this:
// Uses regular expressions to checks if string is not whitespace only
var WHITESPACE = /^\s*$/;
if( WHITESPACE.test(FirstNameValue) && WHITESPACE.test(FirstNameValue)){
How I would fix your code
This would be an incomplete answer if I didn't provide a correct version of your code, so here it goes. Notice that I separate filling-in of information and its validation in two steps.
PatientModel.js :
validate: function(patient){
var WHITESPACE = /^\s*$/;
var errors = [];
if( WHITESPACE.test(patient.FirstName) ){
// No first name
if( WHITESPACE.test(patient.LastName) ){
// No last name either
errors.push('FirstName and LastName are missing');
}
else {
// Only first name missing
errors.push('FirstName is missing');
}
}
else if( WHITESPACE.test( patient.LastName) ){
// Only last name missing
errors.push('LastName is missing');
}
// Returns array of errors
return errors;
}
Your other code:
AddPatient = {};
AddPatient.Firstname = FirstNameValue;
AddPatient.LastName = LastNameValue;
errors = PatientModel.validate(AddPatient);
if( errors.length != 0 ){
alert('You have the following errors:\n' + errors.join('\n'));
}
Edit: a different, perhaps better, approach. The only difference is we now write validate() as a method of a Patient object:
>>> PatientModel.js:
var WHITESPACE = /^\s*$/;
// Creates a new empty Patient
function Patient(){
this.FirstName = '';
this.LastName = '';
}
// Adds a validate() method to all Patient instances
Patient.prototype.validate: function(){
var errors = [];
if( WHITESPACE.test(this.FirstName) ){
// No first name
if( WHITESPACE.test(this.LastName) ){
// No last name either
errors.push('FirstName and LastName are missing');
}
else {
// Only first name missing
errors.push('FirstName is missing');
}
}
else if( WHITESPACE.test( thisLastName) ){
// Only last name missing
errors.push('LastName is missing');
}
// Returns array of errors
return errors;
}
>>> Your other code :
patient = new Patient();
patient.FirstName = FirstNameValue;
patient.LastName = LastNameValue;
errors = patient.validate();
if( errors.length != 0 ){
alert('You have the following errors:\n' + errors.join('\n'));
}
I would recommend using the Jquery validate plugin for this functionality. It will let you do a hole range of clientside validation. Including required validation.
If you just want pure javascript then your method is fine. I'd make it a more generic validate method which would check each validation rule you have and if it fails add the message to an array. After all your checks are finished if the count of the array is grater then zero then output complete list of errors.