Invalid left-hand side in assignment for simple login script - javascript

I have to build a simple login script for a js class.
I cannot get the loop to work. Everytime I type in any info it gives me "Invalid left-hand side in assignment"
When the login button is clicked the getData function gets the values of the boxes then passes them to the logon function that checks against the array. That's where the script stops. If I change the = in the if statement to == it will accept the last valid login f the array but none of the others.
What am I doing wrong?
<script type="text/javascript">
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass = userLogins[i].password && user = userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}

If I change the = in the if statement to == it will accept the last valid login f the array but none of the others.
= is the assignment operator
== is the equality operator
You're confusing the two. You want the latter. Otherwise, your assigning the value which results returns the value itself (often a true value).
Per the comments, there's also the strict equality operator. For the difference between == and === this answer will blow your mind.

Related

html - use onsubmit and action together

I want the form to post the credentials via a get request but have difficulties making it work together with the onsubmit parameter which is used to validate the data entered. This is my form code:
<form onsubmit="return formValidation()" action="show_get.php" method="get" name="registration">
This is the code I used for validation
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
{
if (allLetter(name)) {
if (ValidateEmail(uemail)) {
if (checkDate()) {
}
}
}
return false;
}
}
function allLetter(name) {
var letters = /^[A-Za-z]+$/;
if (name.value.match(letters)) {
return true;
}
else {
alert('Name must have alphabet characters only');
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
}
}
If you attach an onsubmit event handler and it returns false, the form will not be submitted. In your case, that always happens, even if the input is valid.
You check allLetter(), then ValidateEmail() and checkDate(), but you don't return true when they're all valid. Your code continues and it reaches return false;. The submit event handler returns the result of that validation function (which is false), so it returns false too. This tells the form to not submit.
Change your validation function to this:
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
if (allLetter(name) && ValidateEmail(uemail) && checkDate()) {
return true;
} else {
return false;
}
}
If all three checks return true, the validation function will return true as well and the form will be submitted.
Note: You had one unnecessary pair of brackets ({}), I removed them. I also improved readability by combining all the nested if statements into one.
Edit: Also, your checkDate() doesn't return true and false accordingly. It returns undefined by default, which is a falsy value. This means that it won't pass the validation function's && check and the form won't get submitted. Change checkDate() to this:
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
return false;
} else {
return true;
}
}
Edit 2: You also incorrectly get the values of your input elements. When you do this:
var name = document.registration.name;
var uemail = document.registration.email;
You get the HTML element with name attribute name and HTML element with name attribute email. You should get the elements' values:
var name = document.registration.name.value;
var uemail = document.registration.email.value;
It's best to edit your answer and add the full HTML and JavaScript. There might be more problems.

Global variable setting fails in JavaScript validation

I am getting an error while setting global variable flag inside function.
Global variable declaration
var flag = false;
Function to validate textbox
//To validate Product Name field
function Name() {
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
flag = false;
}
else {
$('#productNameError').text('');
flag = true;
}
}
Function to validate quantity
//To validate Product Quantity Field
function Quantity() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
flag = true;
}
else {
$('#productQtyError').text('Enter Quantity of the Product');
flag = false;
}
}
else {
$('#productQtyError').text('Quantity is required');
flag = false;
}
}
//Validation Summary
function validate() {
if (flag == true) {
$('#validationSummary').text('');
return true;
}
else {
$('#validationSummary').text('Please fill out required fields.');
return false;
}
}
I am calling first two functions on onfocusout event of textbox and calling validate() function on button click. The problem which I am facing is: inside the Quantity() flag is not getting set to false. Although the field remains blank,record gets inserted.
if you are getting flag=true in validate() then you may be calling Quantity() first ,it will set flag false then Name() which will set flag to true so It bypassed validate() function.
This is not the correct way, you are trying to achive validation. Consider scenario, when user have entered the correct value in first filed, flag will be set to true with the fact that second field is empty amd form will be submitted and hold true vice versa.
If want to achive by this way, keep as many flag variables as the number of fields amd chech all those variable inside validate.
Or, use '.each' to iterate each element and validate it and keep appending validation mesages to dom object.
Thanks
Don't use Global Variables
You're going to have a bad time if you use global variables, you can use the revealing module pattern to encapsulate some of the messiness
Would suggest something like this :
var app = app || {};
app.product = app.product || {};
app.product.validate = app.product.validate || {};
app.product.validate.isValid = false;
app.product.validate.name = function(){
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
app.product.validation.flag = false;
} else {
$('#productNameError').text('');
app.product.validation.flag = true;
}
}
app.product.validate.quantity = function() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
app.product.validate.flag = true;
} else {
$('#productQtyError').text('Enter Quantity of the Product');
app.product.validate.flag = false;
}
} else {
$('#productQtyError').text('Quantity is required');
app.product.validate.flag = false;
}
}
console.log is Your Friend
Try putting a console.log inside some of those methods, what I am guessing your issue is is that something is being called out of the order you expect and setting the flag to a value you aren't expecting.
Can do console.log statement like this console.log if you open up your developer console should show you the output from the console

Is it possible to assign a value from local function to a global variable in javascript

Hey guys I have declared a global variable in my javascript file.Then iam assigning a value to the global variable in a local function.Then when iam trying to access the value of that global variable in other function,damn alert box is showing 'undefined'.Is there any way to access the value of a local variable in other function.I don't want to call the function from another function and send parameters with it.I just want to access the local variable of one function into some another function.
Hope someone takes me out of this.
Thank you guys and girls.
the code
var user_glob;
var pass_glob;
function osmlogin() {
var user = document.getElementById('uname').value;
var passw = document.getElementById('pwd').value;
user_glob = user;
pass_glob = passw;
if (user == '') {
document.getElementById('wrong_pwd').innerHTML = 'Please give your email_id';
}
else if (passw == '') {
document.getElementById('wrong_pwd').innerHTML = 'Please give your password';
}
else {
var data =
{
username: user,
pass: passw
};
$.getJSON('some url?jsonp=?', data, function (data) {
check = JSON.stringify(data['key1']);
if (check == 1 && user != '' && passw != '') {
window.location.href = "#page-dashboard";
}
else {
// alert(check);
document.getElementById('wrong_pwd').innerHTML = 'Wrong Username or Password';
}
});
}
}
now I want to use that global variable in this function
function announcement_view()
{
var user =user_glob;
var passw = passw_glob;
var data = {
username: user,
pass:passw
};
$.getJSON('some url?jsonp=?', data, function (data) {
var check = JSON.stringify(data['key1']);
alert(JSON.stringify(data['key1']));
alert(JSON.stringify(data['key2']));
if (check == 0 && user == '' && passw == '')
{
//alert(user_glob);
window.location.href = "#page-home";
}
});
}
If your code is something like this...
var a;
function f1(){
a= 1;
}
function f2(){
alert(a);
}
f1();
f2();
It should work fine.
Make sure you are calling the function that assigns the value (f1 in this case) before the function that alerts it (f2 in this case).

Return false from Function within function - Javascript Form Validation

I made a function which validates a form and works fine but I now want to break it down into 3 separate functions.
I now have a function which is called by the form being submitted which declares some arrays and runs the three functions. When it was all one big function the various if statements that found errors would return false; which would then go back to the form and stop it sending.
However now that I've got functions within a function I can't figure out how to get that message 'false' back to the form.
Below is the function called by the form submit button followed by the main function it calls.
I tried creating an empty variable which is returned instead of false which is then is assigned the value false by the validateSignup function but it didn't work.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
passMatch();
genderCountryCheck()
}
function validateText(formNumber, numberElements, errorSpansArrayName, regexErrorArrayName, regexArrayName)
{
for (x = 0; x<numberElements; x++)
{
var spanName = errorSpansArrayName[x];
var textError = document.getElementById(spanName);
var y=document.forms[formNumber].elements[x];
if (!y.value)
{
errorMessage(0,spanName,x);
return false;
}
if(!regexArrayName[x].test(y.value)){
textError.innerHTML = regexErrorArrayName[x];
return false;
}
}
UPDATE:
Thanks for your responses. I have found a solution that seems to work for me.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
var returnValidateText=validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
var returnPassMatch = passMatch();
var returnGenderCountry = genderCountryCheck();
if (returnValidateText || returnPassMatch || returnGenderCountry === false)
{
return false;
}
else{
return true;
}
}
If you call the function it returns a value
var formIsValid = function validateText(....)
should do the trick.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
var formIsValid = false;
formIsValid = validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
formIsValid = passMatch();
formIsValid = genderCountryCheck()
}
One way is to just check the individual function returns directly and return based on that
if (!validateText(0,6,errorSpansArray, regexErrorArray, regexArray)) {
return false;
}
if (!passMatch()) {
return false;
}
if (!genderCountryCheck()) {
return false;
}
Although it's shorter to use a single conditional
return
validateText(0,6,errorSpansArray, regexErrorArray, regexArray) &&
passMatch() &&
genderCountryCheck();
In javascript return false means false will be returned as value where the method is called. So you need something like
If(validateText()){
return true;
}
And similarly rest of the code.

Returning a boolean value in a JavaScript function

I am doing a client side form validation to check if passwords match. But the validation function always returns undefined.
function validatePassword(errorMessage)
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
if(password.value)
{
// Check if confirm_password matches
if(password.value != confirm_password.value)
{
return false;
}
}
else
{
// If password is empty but confirm password is not
if(confirm_password.value)
{
return false;
}
}
return true;
}
Please note that the validatePassword is called from a member function of the Form object.
function Form(validation_fn)
{
// Do other stuff
this.submit_btn = document.getElementById("submit");
this.validation_fn = validation_fn;
}
Form.prototype.submit = funciton()
{
var result;
if(this.validation_fn)
{
result = this.validation_fn();
}
//result is always undefined
if(result)
{
//do other stuff
}
}
You could simplify this a lot:
Check whether one is not empty
Check whether they are equal
This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:
function validatePassword()
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
return password.value !== "" && password.value === confirm_password.value;
// not empty and equal
}
You could wrap your return value in the Boolean function
Boolean([return value])
That'll ensure all falsey values are false and truthy statements are true.
An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. #pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:
function validatePassword() {
const password = document.getElementById("password");
const confirm_password = document.getElementById("password_confirm");
if (password.value.length === 0) {
return false;
}
if (password.value !== confirm_password.value) {
return false;
}
return true;
}
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean

Categories